Search code examples
clinuxternary-operatoroperator-precedence

Comparison operator in for statement


I have a global variable named end_jump which is either 3 or 7.
Depending on what the value is, I want to end a for loop (optimized).
My current code is:

int i;
for(i = 0; i < ((end_jump % 3) == 0) ? 4 : 10; i++){  
    /* do something with */ array[i];  
}  

I'm not getting any error message and the for loop goes on, but doesn't stop. Neither at 4, nor at 10.

Whats the problem?


Solution

  • You're hit by operator precedence.

    Relatrional operators are held in high precedence over the ternary (conditional), hence your loop condition is treated as

     for(i = 0; (i < ((end_jump % 3) == 0)) ? 4 : 10; i++)
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^
    

    where the outcome of the ternary is either 4 or 10, both of them being "truthy", causing the infinite loop.

    You need an extra pair of parenthesis.

    for(i = 0; i < (((end_jump % 3) == 0) ? 4 : 10); i++){  
        /* do something with */ 
    }
    

    should do the job.