I'm familiar with with nested scope rules in C, where same variable name inside the nested block shadows the outer variable with the same name. But for the following code snippet I'm unable to determine the explanation for the output.
#include <stdio.h>
int main()
{
int x = 1, y = 2, z = 3;
printf(" x = %d, y = %d, z = %d \n", x, y, z);
{
int x = 10;
float y = 20;
printf(" x = %d, y = %f, z = %d \n", x, y, z);
}
{
int z = 100;
printf(" x = %d, y = %f, z = %d \n", x, y, z);
}
return 0;
}
The output of the above snippet is:
x = 1, y = 2, z = 3
x = 10, y = 20.000000, z = 3
x = 1, y = 20.000000, z = 2
Will anyone please help me to understand how the value of y
in the third printf statement producing a value of the variable that's out of scope.
First I thought it might be garbage value since printing integer with %f
results in garbage value, so changing the value of y
in the inner scope to some other value results in the same value as output,hence I'm confirmed that it's not a garbage value.
I've compiled the program using gcc version 6.3.1 20161221 (Red Hat 6.3.1-1) (GCC), as well as compiled the program using various online compiler.