In C, you can define a variable at the beginning of any block.
For example, the following is correct (although setting i
to 5 is weird):
int i = 5;
for (i=0; i<1; i++) {
int j = 1;
printf("Value FOR: %d\n", j);
}
Strangely, when doing this in a switch
, the value of j
seems random.
int i = 5;
switch (i)
{
int j = 1;
default:
printf("Value SWITCH: %d\n", j);
break;
}
The piece of code above prints the following on my machine: Value SWITCH: 8
(while it should be Value SWITCH: 1
)
Any idea why?
Could it be because in default
block, it is actually not instantiated and it reads in random memory?
FYI: I am using gcc version 4.6.1 on Windows, if that matters.