Why is this allowed in C??? And what does it do? Full program can be seen here even though it is not necessary http://www.learntosolveit.com/cprogramming/Ex_1.18_remtrailbt.html
for (i > 0; ((s[i] == ' ') || (s[i] == '\t')); --i)
Why is this allowed in C?
Why should it not be allowed? The initialiser part of a for
loop can contain an expression, or a declaration, or just be empty. i > 0
is an expression like any other. Trying to somehow limit what goes there to just expressions with side effects would complicate the language for little benefit.
Compilers are free to emit warnings about such strange code as a Quality of Implementation issue, if they wish.
And what does it do?
Absolutely nothing (unless i
is defined as a macro that does something). It will be ignored.
The first clause of a for
statement is either a declaration or (as in this case) an expression in a void context. What this means is that the first clause is evaluated for its side effects, typically an assignment which is a type of expression.
Section 6.8.5.3 of the C standard defines the for
statement as follows:
1 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 identifiers 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 first evaluation of the controlling expression. If clause-1 is an expression, it is evaluated as a void expression before the first evaluation of the controlling expression.
2 Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.
So any expression is allowed in the first clause of a for
statement. In this particular case the expression i > 0
is evaluated but has no side effect, so it effectively does nothing. It is the same as:
for (; ((s[i] == ' ') || (s[i] == '\t')); --i)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With