+ 1

I am getting confusion about nested ternary operators . Plz help me

Nested ternary operations in c++(i=0?1:2?3:4);

16th Jul 2020, 2:17 AM
Pulasani Aswini
Pulasani Aswini - avatar
9 Antworten
+ 7
Ternary Operator works as follow: (if this is true) ? (do this) : (else, do this); in this case ========== i = 0 ? 1 : 2; 0 is false so 2 must be assigned. "i" will be 2. in this case ========== i = 0 ? 1 : 2 ? 3 : 4; 0 is false so (2 ? 3 : 4) must be assigned to i. in the case of 2 ? 3 : 4, 2 is true and so 3 will be returned. So "i" will be 3. try this cout<<(0 ? 1 : 2 ? 3 : 4); output will be 3. Note: () must include, otherwise the output will be 0.
16th Jul 2020, 3:41 AM
Win Htay 🇲🇲
Win Htay 🇲🇲 - avatar
+ 3
I use to use brackets then, because they make it much more clear. int condition = 2; int result = ( condition == 1 ? 1 : ( condition == 2 ? 2 : 0 ) ); printf("%d", result);
16th Jul 2020, 2:37 AM
Sandra Meyer
Sandra Meyer - avatar
+ 1
Is answer 2 ? For your question
16th Jul 2020, 2:48 AM
Pulasani Aswini
Pulasani Aswini - avatar
+ 1
Tqq friends you all are helped me to clear my confusion . Now I have no doubts about it
16th Jul 2020, 5:26 AM
Pulasani Aswini
Pulasani Aswini - avatar
0
Correct, but you can take the code and try it out what happens, if you set condition = 1 or 2 or something completely different, then you'll see...
16th Jul 2020, 3:13 AM
Sandra Meyer
Sandra Meyer - avatar
0
And you can of course nest it much deeper if you like: int condition = <sth>; // 1 -> 1 // 2 -> 2 // 3 -> 3 // everything else -> 0 int result = ( condition == 1 ? 1 : ( condition == 2 ? 2 : ( condition == 3 ? 3 : 0 ) ) ); printf("%d", result);
16th Jul 2020, 3:15 AM
Sandra Meyer
Sandra Meyer - avatar
16th Jul 2020, 4:11 AM
Navneet Kaur💫
Navneet Kaur💫 - avatar
0
Here's the code just check out
16th Jul 2020, 4:11 AM
Navneet Kaur💫
Navneet Kaur💫 - avatar
0
First we will define the value of i.ex Let I=1... Cout(I=3?2:6) ...it checks the condition if I=3 then it displays the value I=2 else 6 But in this case I=1 this is a false condition then it will execute the else and the value will be 6. Hope you understand if not then ask me
16th Jul 2020, 4:15 AM
Navneet Kaur💫
Navneet Kaur💫 - avatar