+ 1
I am getting confusion about nested ternary operators . Plz help me
Nested ternary operations in c++(i=0?1:2?3:4);
9 odpowiedzi
+ 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.
+ 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);
+ 1
Is answer 2 ? For your question
+ 1
Tqq friends you all are helped me to clear my confusion . Now I have no doubts about it
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...
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);
0
Here's the code just check out
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