0

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's only one single global variable x in the shown code. It's initialized to zero by the system (global non-constant variables are always "zero" initialized). It's increased to 1 in the main function. It's increased to 2 in the g function. The g function prints its value. Then the main function print its value. Commented Oct 10, 2023 at 6:51
  • In the future, please try to use a debugger to step through the code, line by line while monitoring variables and their values, to see what's really is happening. Commented Oct 10, 2023 at 6:52

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.