Nested ternary operator | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Nested ternary operator

Can someone explain me how this works ? int a = (30>20)?(4>1)?20:10:5; outputs T+T = 20 F+F = 5 T+F = 10 F+T = 5

16th Jul 2020, 4:55 PM
Bilgehan Evren
Bilgehan Evren - avatar
4 Answers
+ 2
🇮🇳Vivek🇮🇳 you're missing a closing curly brace '}' for the nested else statement, but otherwise yes that is equivalent.
16th Jul 2020, 5:40 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
if(30 >20) { if(4>1) { return 20 }else { return 10 }else { return 5 } } This is what I think.
16th Jul 2020, 5:05 PM
🇮🇳Vivek🇮🇳
🇮🇳Vivek🇮🇳 - avatar
+ 1
ChaoticDawg thanks for checking.
16th Jul 2020, 5:43 PM
🇮🇳Vivek🇮🇳
🇮🇳Vivek🇮🇳 - avatar
+ 1
#include <iostream> using namespace std; int main() { // Here is Nested ternary operator example int a = (10>20)?(0>1)?20:10:5; cout<<a<<endl; // Solution with if-else if (10>20) cout << "20"<<endl; else if (0>1)cout << "10"<<endl; else cout << "5" << endl; return 0; } /* OUTPUTS T+T = 20 F+F = 5 T+F = 10 F+T = 5 */ // Adding the code here hope it may help others. Thanks for your answers.
16th Jul 2020, 7:25 PM
Bilgehan Evren
Bilgehan Evren - avatar