Why this code output is 0?can anyone elaborate this | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why this code output is 0?can anyone elaborate this

int exp= 1?0:2?3:4; printf("%d",exp);

13th Oct 2020, 6:18 PM
mohana hemanth
mohana hemanth - avatar
4 Answers
+ 2
What i was thinking is since 0 is answer for 1 value 0?3:4 will be taken..so since 0 is false 4 will be printed thats what i thought off
13th Oct 2020, 6:46 PM
mohana hemanth
mohana hemanth - avatar
+ 2
Thanks mate appreciate for that reason and suggestion
13th Oct 2020, 7:14 PM
mohana hemanth
mohana hemanth - avatar
+ 1
Ternary operator exp1 ? exp2 : exp3 If exp1 is is nonzero then exp2 is evaluated and it becomes the value of the whole expression otherwise exp3. 1 ? 0 : (2 ? 3 : 4); 1 is nonzero so 0 is the result of the expression. int exp = 0;
13th Oct 2020, 6:39 PM
Arturop
Arturop - avatar
0
Be careful when nesting ternary operators. Add parenthesis for readability and it also prevents from logic/syntax errors.
13th Oct 2020, 6:58 PM
Arturop
Arturop - avatar