Answer 1: No, the output is not predictable. The first printf()
will write out b=99
, but in the second nested block the
variable a
is not initialized, so you cannot be sure what is printed.
Here is one run of the program:
b=99 a=4139720
I got the above output with Dev-C++ with "Best Optimization" turned on.
Answer 2: In fact, if you run this program you might see:
b=99 a=99
I got that result using exactly the same program and compiler, but with all optimizations turned off.
int main( void ) { int i ; { int b = 99; printf("b=%d\n", b ); } { int a; printf("a=%d\n", a ); } system("pause") ; return 0 ; }
Comments: At run time, a variable exists only when control is inside
the block in which the variable is defined. When control leaves the block, the
variable vanishes. The first inner block defines a variable b
,
which will be created and initialized when control enters the block. When control
leaves the block, b
no longer exists (officially) but the 4 bytes
of main storage that were used for it still exist and still contain a bit pattern.
When the second inner block is entered, variable a
is created
out of main storage. It is likely (but not certain) that the same storage will
be used as was used for b
. This happened in the second run of the
program (above). Optimization sometimes affects what what written programs do.
Ordinarily, you would not have to think such horribly detailed thoughts. But sometimes in debugging programs, problems like this occur. And sometimes, situations like this are exploited by hackers to break into computer systems.