Homework 2 Solution Guidelines
1. There are four int variables called i, one each in blocks 1, 2, 4, and 5. Each printf
statement refers to the variable called i that is visible from it โ remember more specific
declarations โhideโ less specific ones. So the first printf refers to the Block 1 i, the
second one (which is in Block 2), refers to the Block 2 i, the third prinitf (which is
between Blocks 2 and 3, and belongs in Block 1) refers to Block 1 i. The fourth one is in
Block 3, but Block 3 has not defined an i variable of its own, so this printf refers to the
Block 1 i, which is the only one visible to it.
The fifth printf refers to the Block 4 i, and the sixth refers to the Block 5 i defined just
above it. The seventh (last) one is outside all the other blocks, and refers to the Block 1
i.
One point to note is that the variable declaration after a line of source code in Block 5 is
an error according to older standards of C, but is now allowed. Older compilers may
refuse to compile this code โ new ones will compile with a warning.
The wisdom of the warning is clear when trying to trace the output. The first statement in
Block 5 ends up adding to the value of the Block 1 i, not the Block 5 i (as might be
expected or might be the intent of the programmer). This is because when the compiler is
compiling that line, it does not know that a Block 5 i is going to be defined in the next
line. The only i visible to it at that point is the Block 1 i, which is what it uses.
Point to Ponder: What if Block 5 was a loop that ran a few times? What would be the
result of these statements? Try to reason about it before trying it out.
Finally, the output will be:
1 ๏ Block 1 i
2 ๏ Block 2 i
1 ๏ Block 1 i
2 ๏ Block 1 i
4 ๏ Block 4 i
9 ๏ Block 5 i
8 ๏ Block 1 i