Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this piece of code not give error?

Tags:

c

syntax

for-loop

void main() {
    int i, j=6;
    for(; i=j ; j-=2 )
        printf("%d",j);
}

By following regular pattern, there should be a condition after first semicolon, but here it is initialization,so this should have given an error. How is this even a valid format?

But the output is 642

like image 906
Nitish Prajapati Avatar asked Dec 10 '25 19:12

Nitish Prajapati


2 Answers

First, let me correct the terminology, the i=j is an assignment, not an initialization.

That said, let's analyze the for loop syntax first.

for ( clause-1 ; expression-2 ; expression-3 ) statement

So, the expression-2 should be an "expression".

Now, coming to the syntax for statement having assignment operator

assignment-expression:
conditional-expression
unary-expression assignment-operator assignment-expression

So, as the spec C11 mentions in chapter §6.5.16, the assignment operation is also an expression which fits perfectly for the expression-2 part in for loop syntax.

Regarding the result,

An assignment expression has the value of the left operand after the assignment,

so, i=j will basically assign the value of j to i and then, the value of i will be used for condition checking, (i.e., non-zero or zero as TRUE or FALSE).

TL;DR Syntactically, there's no issue with the code, so no error is generated by your compiler.


Also, for a hosted environment, void main() should be int main(void) to be conforming to the standard.

like image 100
Sourav Ghosh Avatar answered Dec 12 '25 13:12

Sourav Ghosh


i=j is also an expression, the value of which is the value of i after the assignment. So it can serve as a condition.

You'd normally see this type of cleverness used like this:

if ((ptr = some_complex_function()) != NULL)
{
  /* Use ptr */
}

Where some programmers like to fold the assignment and check into one line of code. How good or bad this is for readability is a matter of opinion.

like image 25
StoryTeller - Unslander Monica Avatar answered Dec 12 '25 11:12

StoryTeller - Unslander Monica