Martin Ambuhl said:
It is considered a good thing to post compilable code. It would not
have been difficult for you to turn the above snippet into such by
simply embedding the above with in an
int main(void)
{
/* the above */
return 0;
}
[snip]
It can also be helpful to add output statements so you can see what's
going on as the program runs.
For the purposes of this exercise, it would be best to trace through
the original code manually, and perhaps to verify the answer by adding
a printf("j = %d\n", j) statement after the end of the code fragment.
This problem is really simple enough that more intrusive methods
aren't necessary.
But since the answer has already been posted, here's a version of the
code as a complete program that shows what happens at each step:
#include <stdio.h>
int main(void)
{
int i, j;
for( printf("loop1, i = 0\n"), i = 0;
printf(i < 1 ? "loop2, continuing\n" : "loop2, quitting\n"), i < 1;
printf("loop3, i++\n"), i++ )
{
printf("Top of loop, i = %d\n", i);
switch( i )
{
case 0: i += 5; printf("i += 5, fall through\n");
case 3: i += 3; printf("i += 3, fall through\n");
case 5: i += 5; printf("i += 5, break out of switch\n");
break;
}
printf("Bottom of loop, i = %d\n", i);
}
j = i;
printf("j = %d\n", j);
return 0;
}
I've also made the code C90-compliant by moving the declaration of j.
Each of the three parts between the parentheses of a for statement is
an expression. A function call is also an expression. Here, I use
the comma operator to insert a printf() call into each expression; the
value returned by printf() is discarded, and the new expression yields
the same result as the original one would have.
(Using a debugger would be another way to trace the execution of the
code, but different debuggers work differently, and the details are
off-topic.)