1

If we have a variable "x" which is defined globally and another variable with the same name "x" inside a function. when we print the value of "x" why we always get the value which is assigned inside the function? Is there any way we can print the global variable value.

int x=8;
void testCode()
{
    int x=2;
    printf("%d",x); //prints 2
}
user968000
  • 1,765
  • 3
  • 22
  • 31
  • Note that GCC can warn about this with the `-Wshadow` option, although this is not enabled by any of `-Wall`, `-Wextra`, or `-pedantic`. – Adam Rosenfield Sep 17 '13 at 19:47

4 Answers4

5

In other languages, yes. In C, there is no way to access the global in the same scope. There is a way to declare a nested scope (see other answers) which would give you access to a non-static global, but it is not recommended - don't do it. If you want to get the global variable, don't hide it with a local variable of the same name.

Mark Lakata
  • 19,989
  • 5
  • 106
  • 123
1

You can print global over local in following manner:

int a=6;
int main()
{
  int a=5;
  printf("%d",a);
  {
    extern int a;
    printf("%d",a);
  }
}
Mayank Jain
  • 2,504
  • 9
  • 33
  • 52
1

You can do something like this:

int x = 8;
void testCode()
{
    int x=2;
    printf("%d",x); //prints 2

    {
        extern int x;
        printf("%d", x); // prints 8
    }
}
0xdead10cc
  • 521
  • 4
  • 6
1

In C When Local variables Have same Name as Global variables then Local variable get highest priority.

This is why we are always getting the local variable values when printing.

if you print out side the blcok of local variable then will prints GLOBAL Value.

You can print global value by calling another function.where you did not declare local variable with the same name

Example:

int i=20;
int get_global();
main()
{
int i=5;
printf("LOCAL=%d",i));
printf("GLOBAL=%d",get_global());
}
int get_global()
{
return i;
} 
Gangadhar
  • 10,248
  • 3
  • 31
  • 50