Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

gcc

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 <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;           
}

Why and is there any way to print it in c ? ... BTW I know it in c++.

like image 544
Omkant Avatar asked Aug 29 '12 18:08

Omkant


1 Answers

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; 
}
like image 178
ouah Avatar answered Sep 28 '22 02:09

ouah