extern storage class output

54 Views Asked by At

somy question is, **Is there two variable named x in the main ,one goes to g() with value 1 go there prints 2 and another one keeps at 1 again prints 2 in main. **

#include <stdio.h>
void f(){
    extern int x;
    
    x++;
    printf("%d",x);
    
}
  int x;
void g(){
   
    ++x;
    printf("%d",x);
}
int main() {
    // Write C code here
    x++;
    g();
    
    printf("%d",x);

    return 0;
}

Output : 22

2

There are 2 best solutions below

0
On BEST ANSWER

Here x in main and the one defined outside g() in global scope are referring to the same x. Also the variable x is extern through out the code because of the previous declaration.

Try printing the address of x in the required location.

Refer this answer for more info

0
On

Is there two variable named x in the main

No, there is only one and it has static storage duration. It was defined just above the g() function definition.

You could check it yourself by adding something to your printfs:

void f(void)
{
    extern int x;
    
    x++;
    printf("%d %p\n", x, (void *)&x);
}

int x;

void g(void)
{
    ++x;
    printf("%d %p\n", x, (void *)&x);
}

int main(void) 
{
    x++;
    g();
    printf("%d %p\n", x, (void *)&x);
}

and the output:

2 0x40401c
2 0x40401c

https://godbolt.org/z/sxYnfzqhP