Mr. Nex
Mr. Nex

Reputation: 233

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?

Upvotes: 4

Views: 752

Answers (3)

too honest for this site
too honest for this site

Reputation: 12263

Try:

i < ((numRows + 1) / 2)

If numRows is even, it will just be numRows/2. If odd, it will be numRows/2+1.

That will be faster and avoids branching due to the compare (unless you have a n excelent compiler which knows this pattern - unlikely.

You sometimes have to step back to see the whole picture.

Upvotes: 1

Sourav Ghosh
Sourav Ghosh

Reputation: 134376

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.

Upvotes: 10

Varga Robert
Varga Robert

Reputation: 11

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)

Upvotes: 1

Related Questions