Search code examples
cfor-loopcomparison-operators

Whats happening in this for loop


whats happening in the first statement of the for loop? I can not seem to wrap my head around why 1 == 2 would be acceptable because its a comparison and not a value assignment.

char ch = 120;
unsigned char x = 1;
unsigned int y = 1;
for(1 == 2; ch > 0; ch++) {
  printf("%d\n", ch);
  x <<= 1;
  y *= 2;
}

Solution

  • It is just a useless statement that the compiler will optimize away. The first statement in the for does not need to be an assignment, it is just build to be succinct/readable way to loop over a set of values. You can expand the for loop into a while and it may make it clearer:

    1 == 2; // does nothing, likely emits compiler warning.
    while( ch > 0 )
    {
        printf("%d\n", ch);
        x <<= 1;
        y *= 2
    
        ch++;
    }
    

    If you want to use a for loop for the post iteration expression but have already initialized your variables, you can use the null statement as the first expression:

    for( ; ch > 0; ch++ ){ /* ... */ }