c - Ternary Operator in For Loop causing infinite iterations -


i working on function transpose nxn matrix stored in array of floats. first implementation seemed cause function loop infinitely , can't seem figure out why. here original code:

for(int = 0; < numrows % 2 == 0 ? numrows / 2 : numrows / 2 + 1; i++) {     for(int j = + 1; j < numcolumns; j++)     {         //swap [i,j]th element [j,i]th element     } } 

however function never returns. failing see error in logic rephrased expression , have following working code:

int middlerow =  numrows % 2 == 0 ? numrows / 2 : numrows / 2 + 1; for(int = 0; < middlerow; i++) {     for(int j = + 1; j < numcolumns; j++)     {         //swap [i,j]th element [j,i]th element     } } 

can explain why first version not work seemingly equivalent second version does?

as per operator precedence table, < has higher priority on ?:. need use () required explicitly enforce required priority.

change

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

to

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

note: please use second approach. much, better in readability, maintenance , understanding.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -