'Same variable as global and local in C
I'm getting answer i = 2. But my question is what happened to i=0??? According to my understanding i=0 will be in DATA SEGMENT I=2 will be in STACK SEGMENT
#include <stdio.h>
int i = 0;
void main()
{
int i = 2;
printf("i value is %d\n",i);`
}
Solution 1:[1]
Local variable i hides the global variable i. Hence, when you print it, it'll print the local variable.
If you want modify the global variable, you can use the idea mentioned here:
Solution 2:[2]
Shadowing. Your global variable i = 0 is shadowed by local i = 2.
Don't do it, avoid name collisions.
By the way, void main() {} is not standard C (assuming your program is running in a hosted environment, i.e. on top of an OS). Use int main(void) { return 0; } instead. Reference. Another one.
Solution 3:[3]
You have declared a local variable with the same name as your global variable, hiding it by making i (when used within the very same scope where your local variable has been declared) refer to your local variable rather than the global one.
The most natural and logical solution for this is: Avoid doing it always when possible.
Solution 4:[4]
It is the variable scope working out here. If you have multiple variables of same type is declared, the operator available with the near most scope will get accessed.
The scope resolution will happen in the compile time. When the compiler search for any variable declaration when it is accessed in the code, it will first look in the nearest scope and then go up. The global, variable will be accessed last.
Solution 5:[5]
Suppose you have a global variable name i and you have two functions function1 and function2. In both functions, you printed the value of i. In function1 you have declared the value of i again. So in function1 you have a local variable i.
#include<stdio.h>
int i = 10;
void function1()
{
int i = 20;
printf("%d\n", i);
}
void function2()
{
printf("%d", i);
}
int main()
{
function1();
function2();
return 0;
}
The compiler will consider the local variable i in function1 and print 20. On the other hand in the function2, there is no local variable named i. So it will print the global variable i = 10.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
| Solution 2 | Community |
| Solution 3 | LihO |
| Solution 4 | joe |
| Solution 5 | Muhammad Mohsin Khan |
