The C for() loop - A strange observation

Hello,

I am optimizing my low level C coding style.

I have run into an strange C implementation fact:
----------------------------------------------------

unsigned int X;

for ( X = 0; X < 10; X++ ) printf("%u\n",X);

Produces:
0
1
2
3
4
5
6
7
8
9
----------------------------------------------------

unsigned int X;

for ( X = 10; X-- > 0; ) printf("%u\n",X);

Produces:
9
8
7
6
5
4
3
2
1
0
---------------------------------------------------

In the first case, the X++ operation is completed after the body of the loop, so the initial value of X is run through the loop.

In the second case, the X-- operation is completed before the body of the loop, so the initial value of X is skipped in the loop.

Why?

Is the final expression in the for() loop tied to the {} braces, whereas the loop condition is taking place distinctly before the {} braces?

All the Best,

Heavy J

  • Will the second loop really execute faster? or does compiler optimization take care of that problem even when the condition and initial value are not constants?

Not very strange. Your second example relates to a controlling expression which is always evaluated before each execution of the for loop. See ISO C99 6.8.5.3.

The statement for ( clause-1 ; expression-2 ; expression-3 ) statement
behaves as follows: The expression expression-2 is the controlling expression that is
evaluated before each execution of the loop body. The expression expression-3 is
evaluated as a void expression after each execution of the loop body. If clause-1 is a
declaration, the scope of any variables it declares is the remainder of the declaration and
the entire loop, including the other two expressions; it is reached in the order of execution
before the rst evaluation of the controlling expression. If clause-1 is an expression, it is
evaluated as a void expression before the rst evaluation of the controlling expression.
Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a
nonzero constant.

Thank you for the answer...

Is there any difference between these two loops?

for ( X = 0; X < 10; X++ ){
use X;
}

for ( X = 0; X < 10; ++X ){
use X;
}

No.. expression-3 is something that is executed after the body of the for statement. Then its back to the expression-2 evaluation.