The ternary operator in For Loop causing infinite iterations

I worked on the matrix transpose function NxN, which is stored in the floats array . My first implementation seemed to force the loop function endlessly, and I can't figure out why. Here is the source 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. Having not received an error in my logic, I rephrased the expression and now I got 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
    }
}

Does anyone help explain why the first version does not work, but seems to be equivalent to the second version?

+4
source share
3 answers

, < ?:. (), , .

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

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

: . , , .

+10

, . ( ), :

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

Try:

i < ((numRows + 1) / 2)

numRows , numRows/2. , numRows/2 + 1.

- ( n excelent, - .

, .

+1

Source: https://habr.com/ru/post/1584578/


All Articles