Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice to use "ternary operation" in the "for" loop condition?

Is it a good practice to use ternary operation in for loop condition. I am asking this because i have come across the situation where in ternary operation will resolve my issue in for loop condition.

For eg:

for( short i = 0 ; i < count ; i++ ){
   for( short j = 0 ; j < ( ( x[i] < y[i] ) ? x[i] : y[i] ) ; j++ ){ //Here I am using ternary operation at for loop condition place
       //.....
       //.....Some Code Here .......
       //.....
   }
}
like image 244
Abhineet Avatar asked Nov 20 '25 17:11

Abhineet


2 Answers

I'd go for min(x[i], y[i]), just because it's clearer, but I don't see an immediate problem with your code.

like image 82
Xeo Avatar answered Nov 23 '25 07:11

Xeo


Personally I would go for min(x[i], y[i]). However, your readability issues can be dealt with by pre-calculating the value and using it:

for( short i = 0 ; i < count ; i++ ){
   int jCount = ( x[i] < y[i] ) ? x[i] : y[i]; // or min equivalent
   for( short j = 0 ; j < jCount ; j++ ){ 

   }
}

This changes the behaviour somewhat, in that it makes the condition blind to changes to x[i] and y[i] inside the j loop. I am not sure if that fits your use-case or not.

like image 31
juanchopanza Avatar answered Nov 23 '25 08:11

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!