All,
Consider the following code:
void func(void)
{
int a;
printf ("%d", a);
}
int main(int argc, char **argv)
{
int a = 3;
func();
printf("%d", a);
}
According to my understanding, the output should be:
<junk value><3>
Can anyone please confirm my understanding? My basic query is, does the compiler refer to the outer scope for a variable that has been declared but not defined?
Regards,
darkie
Your understanding is correct.
func‘sais initialized with stack trash.Each time you say
int a;, it will create a new variable, with no relation to similarly named variables from enclosing scopes or variables from other functions higher up the call-stack.In your justification, you’re confusing Scope and Extent. c uses lexical scoping, so while
main‘s “extent” (or liftime) exists through the execution offunc, it is an entirely different scope, so it refers to an entirely different variable.Note that an “outer scope” is usually the braces outside of yours, with the outermost scope being file level.
Each one of those ‘a’ variables shadows the other ‘a’s above it.
The exception (maybe the source of your confusion) being a variable declared
extern int a;. This variable specifically refers to a variable from somewhere else (different translation unit). An external declaration may be used to get the behavior you were not expecting:The exceptions to the “stack trash” rule are that
staticand heap allocated variables are zero initialized (if I am not mistaken, this is enforced by the standard).And also note that “garbage value” might be 3.