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?
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.
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)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With