Search code examples
cscopedeclarationlinkage

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


I had this assignment at school, wherein I had to find the output of the following C code, and also, to explain the output.

#include<stdio.h>
int i;
void fun1(void);
void fun2(void);
int main()
{
    fun1();
    fun2();
    return 0;
}

void fun1(){
    i=20;
    printf("%d\t",i);
}

void fun2(){
    int i=50;
    printf("%d",i);
}

The output is 20 50 Because in fun1() the Global Variable 'i' is assigned to 20 and printed. And in fun2() the variable 'i' is a Local Variable, which is declared and initialized to 50, which is then printed.

I have this following question out of curiosity, how do I use the global variable 'i', in fun2()? A simple solution would be to simply change the name and avoid the whole thing. But my curiosity is due to Java, where there is a keyword "this" to access class variable instead of a local variable.

so is there any way to do that in C?


Solution

  • 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.