Search code examples
cfor-loopinfinite-loopternary-operatoroperator-precedence

Ternary Operator in For Loop causing infinite iterations


I was working on a function to transpose an NxN matrix which is stored in an array of floats. My first implementation seemed to cause the function to loop infinitely and I can't seem to figure out why. Here is the original code:

for(int i = 0; i < numRows % 2 == 0 ? numRows / 2 : numRows / 2 + 1; i++)
{
    for(int j = i + 1; j < numColumns; j++)
    {
        //Swap [i,j]th element with [j,i]th element
    }
}

However the function never returns. Failing to see the error in my logic I rephrased the expression and now have the following working code:

int middleRow =  numRows % 2 == 0 ? numRows / 2 : numRows / 2 + 1;
for(int i = 0; i < middleRow; i++)
{
    for(int j = i + 1; j < numColumns; j++)
    {
        //Swap [i,j]th element with [j,i]th element
    }
}

Can anybody help explain why the first version does not work but the seemingly equivalent second version does?


Solution

  • As per the operator precedence table, < has higher priority over ?:. You need to use () as required explicitly to enforce the required priority.

    Change

    for(int i = 0; i < numRows % 2 == 0 ? numRows / 2 : numRows / 2 + 1; i++)
    

    to

    for(int i = 0; i < ( numRows % 2 == 0 ? numRows / 2 : numRows / 2 + 1) ; i++)
    

    Note: Please use the second approach. Much, Much better in readability, maintenance and understanding.