How to print value of global variable and local variable having same name?

前端 未结 4 898
别那么骄傲
别那么骄傲 2020-12-03 15:00

Here is my code , I want to print 15 and 12 but due to instance member hiding the local value of a is getting printed twice.

#include                  


        
相关标签:
4条回答
  • 2020-12-03 15:23

    add :: for global ambit

    #include <stdio.h>                                  
    int a=12;             
    int main()          
    {           
      int a=15;             
      printf("Inside a's main local a = : %d\n",a);                  
      printf("In a global a = %d\n",::a);            
      return 0;           
    }
    
    0 讨论(0)
  • 2020-12-03 15:25

    I know this doesn't directly answer your question, but the best way to do this is to change the name of the local variable so it doesn't conflict with the name of the global variable.

    If you have control of the code inside the function (i.e., you can add an extern declaration to make the global variable visible), then you can just as easily change the name of the variable.

    It's impossible to tell what name would be better. In practice, the variables will undoubtedly have more descriptive names than a. The way they're used should give you some guidance about good names for them.

    If they actually serve the same purpose, they probably don't both need to exist. You might remove variable that's local to main(), or, perhaps better, remove the global and pass the local (or its address) to other functions that need to access it.

    0 讨论(0)
  • 2020-12-03 15:33

    Use the extern specifier in a new compound statement.

    This way:

    #include <stdio.h>      
    
    int a = 12;             
    
    int main(void)          
    {           
        int a = 15;             
        printf("Inside a's main local a = : %d\n", a);
    
        {
            extern int a;
            printf("In a global a = %d\n", a);
        }
    
        return 0; 
    }
    
    0 讨论(0)
  • 2020-12-03 15:33

    I think i found my answer in a way... it works

    #include <stdio.h>
    
    int a = 5;
    
    
    int main()
    {
        int a=10;
        if(1)
        {
            extern int a;
            printf("global: %d\n", a);
        }
        printf("local: %d\n", a);
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题