+ 1
Why doesn't ternary work inside of loops?
I was working on the Crypto-Cube challenge and I decided to use classes and ternaries (new things for me). They worked fine, but I wasn't able to use the ternary inside a loop, however as soon as I created a variable and set that equal to the ternary, it worked like a charm and I was wondering why we can't use ternary inside loops.
6 Réponses
+ 2
wrap the ternary with parentheses like this:
#include <iostream>
using namespace std;
int main() {
int n = 9;
for(int i =0; i<n; i++){
for(int j=0; j< (( i == n - 1 ) ? 5 : 8); j++)
cout<<"No "<<j<<endl;
}
return 0;
}
+ 3
Androidus i think it gets evaluated like this (j<(i==n-1))?5:8, when i instead use brackets like this: j<((i==n-1)?5:8) it terminates
+ 2
could you share your code?
+ 2
You can use ternary inside of loops. Can you give us some example code for context?
+ 2
Thanks for the explanation
+ 1
Mohamed ELomari
ODLNT
I can't provide the exact code I had because I have changed it since it gave me the error, but this is some sort of example where it causes an infinite loop:
https://code.sololearn.com/cbpMabfOEcHU/?ref=app