rnsanchez
rnsanchez

Reputation: 89

Evaluation order in a for-loop initialization in C

Consider this C-snippet:

int a;
int b;
for (a = 0, b = a + 1; a < N; a++)
    /* Something. */

Does the C specification clearly requires a compiler to keep the statements in the for-initializer in the order they appear?

I am specifically trying to avoid undefined behavior, if, for example, a was in an outer/global scope and the specification was not strict in this specific area. In other words, I want to be sure that the example above has a clear definition for compilers, and not enter gray areas such as a = ++a + b++;.

Upvotes: 1

Views: 887

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

Not specially in the for-initializer, the expression in left of comma operator (a = 0) will be evaluated first, then the right (b = a + 1) will be evaluated.

N1256 6.5.17 Comma operator

The left operand of a comma operator is evaluated as a void expression; there is a sequence point after its evaluation. Then the right operand is evaluated; the result has its type and value.

Upvotes: 2

Related Questions