How to Access a Global Variable Within a Local Scope

How to access local and global variable with same name in C

You could cheat and create a pointer to the global i before declaring the local i:

void fun2( void )
{
int *ip = &i; // get address of global i
int i = 50; // local i ”shadows" global i

printf( "local i = %d, global i = %d\n", i, *ip );
}

EDIT

Seeing as this answer got accepted, I must emphasize that you should never write code like this. This is a band-aid around poor programming practice.

Avoid globals where possible, and where not possible use a naming convention that clearly marks them as global and is unlikely to be shadowed (such as prefixing with a g_ or something similar).

I can't tell you how many hours I've wasted chasing down issues that were due to a naming collision like this.

How to access local variable after global keyword in python

Give the local variable a different name. global applies for the entirety of the function, you can't switch back and forth as you go. The best you could do is cheap hacks to access the global (globals()['var']) while leaving the name local, but don't do this. Use different names.

Using global variables in a function

You can use a global variable within other functions by declaring it as global within each function that assigns a value to it:

globvar = 0

def set_globvar_to_one():
global globvar # Needed to modify global copy of globvar
globvar = 1

def print_globvar():
print(globvar) # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar() # Prints 1

Since it's unclear whether globvar = 1 is creating a local variable or changing a global variable, Python defaults to creating a local variable, and makes you explicitly choose the other behavior with the global keyword.

See other answers if you want to share a global variable across modules.

How to access a global variable within a local scope?

You should be using ::x in order to access global variable in local scope. The operator :: is unary scope resolution operator. So your code should be:

   #include <iostream>
using namespace std;
int x = 5;
int main()
{
int x = 1;
cout << "The variable x: " << ::x << endl;
}

Note: :: operator has two meanings in C++:

  1. Binary scope resolution operator.
  2. Unary Scope resolution operator.

Almost for your entire coding hours, you would be using the Binary scope resolution operator. So although the answer to this question is unary scope resolution operator; just for the sake of future reference, I enlist some typical use cases of the Binary scope resolution operator.

Use cases of the Binary scope resolution operator:

1. To define your functions outside the class.

We organize our code into header files with .h extension and code files with .cpp extension. While defining our functions in the code files, we use the :: Binary scope resolution operator.

For example,a Car.h file looks like:

class Car
{
private:
int model;
int price;

public:
void drive();
void accelerate();
};

And Car.cpp would look like:

void Car :: drive()
{
// Driving logic.
}
void Car :: accelerate()
{
// Logic for accelerating.
}

Here, as we can easily notice, :: acts on two operands:

  1. The class name
  2. The function name

Hence, it essentially defines the scope of the function i.e. it informs the compiler that the function drive() belongs to the class Car.


2. To resolve ambiguity between two functions with same template which are derived from different classes.

Consider the following code:

#include <iostream>
using namespace std;
class Vehicle
{
public:
void drive()
{
cout << "I am driving a Vehicle.\n";
}
};
class Car
{
public:
void drive()
{
cout << "I am driving a Car.\n";
}
};
class BMW : public Car, public Vehicle
{
// BMW specific functions.
};
int main(int arc, char **argv)
{
BMW b;
b.drive(); // This will give compile error as the call is ambiguous.
b.Car::drive(); // Will call Car's drive method.
b.Vehicle::drive(); // Will call Vehicle's drive method.
}

As both the derived functions of the class BMW have the same template, the call b.drive will result into a compilation error. Hence, to specify which drive() we want, we use the :: operator.


3. To override the overridden function.

Binary scope resolution operator helps to call the function of the base class which is overridden in a derived class using the derived class's object. See the code below:

#include <iostream>
using namespace std;
class Car
{
public:
void drive()
{
cout << "I am driving Car.\n";
}
};
class BMW : public Car
{
public:
void drive()
{
cout << "I am driving BMW\n";
}
};
int main(int argc, char** argv)
{
BMW b;
b.drive(); // Will call BMW's drive function.
b.Car::drive(); // Will call Car's drive function.
}

4. To access static data members.

As we know, static data members are shared per class basis by the objects of that class. Hence, we should not (although we can) use objects to scope the static variables. See the following code:

#include <iostream>
using namespace std;
class Car
{
public:
static int car_variable;
};
int Car :: car_variable;
int main(int argc, char** argv)
{
Car :: car_variable = 10;
cout << "Car variable: " << Car :: car_variable << '\n';
return 0;
}

how to access global variable within __main__ scope?

global isn't global. global is module-level; truly global variables like min and int live in the __builtin__ module (builtins in Python 3). Using a global declaration at module level is redundant.

I strongly recommend you pass your data to test.py another way, such as by defining a function in there and passing your string as an argument:

test.py:

def print_thing(thing):
print thing

other code that wants to use test.py:

import test
test.print_thing("Joe")

How can I access global variable inside class in Python

By declaring it global inside the function that accesses it:

g_c = 0

class TestClass():
def run(self):
global g_c
for i in range(10):
g_c = 1
print(g_c)

The Python documentation says this, about the global statement:

The global statement is a declaration which holds for the entire current code block.



Related Topics



Leave a reply



Submit