in Programming in C
525 views
1 vote
1 vote

I know the answer but need a good explanation for this question. Can anyone help. Thanks!

in Programming in C
525 views

1 comment

C++ | Nested Ternary Operator - GeeksforGeeks

i+1*i+2 is = 4 means true. --i will be returned which is 0.

While(0)

// Nothing will be printed.

Now i is 0 and j is 1.

1
1

2 Answers

1 vote
1 vote
Best answer
Associativity of ternary operator is right to left, and precedence of ternary operator is only greater than assignment operators which doesn’t exist in the while condition.

Thus first j ? i*3 : --j is executed, leading to the value of 3.

Now the first ternary operator is executed. Since precedence of addition/ multiplication are higher than ?: hence

i + 1*i + 2 is executed which gives value of 4 which is true value. thus the ternary operator replaces the condition statement with --i which decrements the value of i to 0 and returns 0. thus while loop exits.

Hence printf prints 0

Hope this helps
selected by

2 Comments

Thanks! got it.
0
0
If while(0) then no printf statement will execute.. then ans will be option d.. isn't it?
0
0
0 votes
0 votes
it prints nothing option d is right.