Your teacher is wrong, but not entirely.
Variables declared within a function are by default auto
rather than static
.
int foo(void) {
static int x;
int y;
auto int z;
/* ...other code... */
}
This means that in the function above y
is auto, just like z, even though the auto
keyword is not used in its declaration. The auto
keyword is almost never used, by the way. Many C (and C derivative language) programmers don't even know that auto
is a keyword because it is used so infrequently.
Being an auto
variable usually means that the variable is stored on the program's system stack or in registers or some mix of these. It can be at different places at different times during the course of execution of the function, and local variables that are in registers are often pushed to the stack when another function is called. Some local variables may even be optimized away, meaning that at some point the compiler was able to determine that a particular variable's future value was no longer needed to satisfy the input needs of the future code (or the variable doesn't change and its value is just encoded within instructions). This complicates using debuggers on optimized code.
When you take the address of a local variable the compiler then tries to lock it down to a specific address (probably by storing it on the stack).
When most compilers look at your code they will see that the names of those local variables are not used after their declaration and may decide to just not store their values anywhere. Even if it does store those values on the stack it may also push other values on the stack before setting up to call printf
. Just as the compiler does not have to keep the variables you named around it is also free to create it's own temporary variables.