janardhan tj
janardhan tj

Reputation: 29

Global and local variable with the same name, unexpected value

I have both a local and a global variable with same name.

int var = 10;
int main() {
    int var = var;
    printf("%d", var);
    return 0;
}

Running the program gives this output: 0

Why is that?

Upvotes: 2

Views: 2298

Answers (2)

Lundin
Lundin

Reputation: 213842

The global variable has nothing to do with it, you can comment out that line of code. When the compiler finds a local variable with the same name as a variable in another, outer scope, the local variable will always be used.

Therefore both "var" in the expression int var = var; refers to itself: the local variable. It doesn't make any sense to initialize a variable to its own uninitialized value. The value will remain indeterminate and when you use the value in your program you invoke undefined behavior: anything can happen.

Upvotes: 4

Peter
Peter

Reputation: 36597

The int var = var in main() does not actually access the var at file scope.

The result is actually undefined behaviour, since it tries to access the value of the local var which has not been initialised. So any result you get (zero, 42, reformatting your hard drive) is valid.

Try building your code with a different compiler, and you could well get a different output.

Out of curiosity, I compiled, built, and ran the same code (other than adding #include <stdio.h>) and the output I received was 41944322. The compiler on my current machine is gcc 4.8.1 (mingw).

Upvotes: 2

Related Questions