hello,
I am really confused over following for code snippets. No problem
that they are working codes but how? how they are evaluated by
compiler? It will be my pleasure if you explain me all following
snippets.
This smells like homework, but I feel generous today.
1) {
int i=3;
for (i--; i<7; i=7)
printf("%d",i++);
}
1. i is initialized to 3
2. the i-- expression is evaluated; i now equals 2
3. the i<7 expression is evaluated; 2 < 7 == true, so the loop body is
executed
4. the printf() statement is executed; as a side effect, i is
incremented by 1, and now equals 3 again
5. the i=7 expression is evaluated; i now equals 7
6. the i<7 expression is evaluated; 7 < 7 == false, so the loop exits
2) {
int i;
for (i=5; --i
printf("%d",i);
}
1. i is declared with no initial value
2. the i=5 expression is evaluated; i now equals 5
3. the --i expression is evaluated; the resulting value (4) is
non-zero (true), so the loop body is executed
4. print the current value of i (4)
5. There is no update expression to evaluate
6. Repeat steps 3 through 5 should be three more times
7. the --i expression is evaluated; the resulting value is 0 (false),
so the loop exits
3) {
int i;
for (i=-10; !i; i++);
printf("%d",-i);
}
1. i is declared with no initial value
2. the expression i=-10 is evaluated; i now equals -10
3. the expression !i is evaluated; since -10 is non-zero (true), the
expression !i evaluates to 0 (false), and the loop exits without doing
anything.
4) {
int i;
for (;(i=4)?(i-4):i++
printf("%d",i);
}
1. i is declared with no initial value
2. there is no initialization expression
3. the expression (i=4) is evaluated; if the result is non-zero (which
it is, since the result of i=4 is 4), then the expression i-4 is
evaluated, otherwise the expression i++ is evaluated. Since the
expression i-4 is evaluated, the result is 4-4, or 0 (false), so the
loop exits without doing anything.
5) {
static int j;
for (j<5; j<5; j+=j<5)
printf("%d",j++);
}
1. j is declared with no initial value but with static extent; this
implicitly initializes j to zero.
2. the first j<5 expression is executed; the result is 1 (true)
3. the second j<5 expression is evaluated; the result is 1 (true), so
the loop body is executed
4. the printf() statement is executed; as a side effect, j is
incremented by 1.
5. the expression j+=j<5 is evaluated; the result of the expression j
< 5 (1 if j is less than 5, 0 if j is greater than or equal to 5) is
added back to j.
6. repeat steps 3 through 5 until j >= 5 (should be two more times).