The output of the following code is 0.
int account=2;
int main()
{
static int account;
printf("%d",account);
return 0;
}
Why it picked static variable over global variable? Because what I understand is that both global and static variables are stored in the heap and not in function stack , right? So what method it uses to use select one over another?
If multiple variables exist with the same name at multiple scopes, the one in the innermost scope is the one that is accessible. Variables at higher scope are hidden.
In this case you have account
defined in main
. This hides the variable named account
declared at file scope. The fact that the inner variable inside main
is declared static
doesn't change that.
While the static
declaration on a local variable means that it is typically stored in the same place as a global variable, that has no bearing on which is visible when the names are the same.