Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 718
Mr. Nex Avatar asked Dec 14 '22 15:12

Mr. Nex


2 Answers

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.

like image 129
Sourav Ghosh Avatar answered Jan 04 '23 22:01

Sourav Ghosh


I think there is a problem with the precedence of the operators. If you want to keep the cluttered first version (which I don't recommend) use parenthesis:

i < (numRows % 2 == 0 ? numRows / 2 : numRows / 2 + 1)
like image 29
Varga Robert Avatar answered Jan 04 '23 22:01

Varga Robert