Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using condition instead of assignment in first part of for header in C

Tags:

c

loops

for-loop

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)
like image 410
Michael Avatar asked Mar 03 '23 10:03

Michael


2 Answers

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.

like image 71
Angew is no longer proud of SO Avatar answered Mar 29 '23 22:03

Angew is no longer proud of SO


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)
like image 28
dbush Avatar answered Mar 30 '23 00:03

dbush