in Programming in C retagged by
1,099 views
9 votes
9 votes

What will be the output of the following C program?

#include<stdio.h>
void main()
{
    int a =0;
    int b = (a-- ? a++: a ? a++ : a-- );
    printf("%d", b);
}
  1. $0$
  2. $-1$
  3. $-2$
  4. $2$
in Programming in C retagged by
1.1k views

2 Comments

2
2
In the solution the precedence is not explained properly.
0
0

1 Answer

14 votes
14 votes

a = 0

b = a– –  ? a++ : a ? a++ : a– –  $\equiv$  b = a– –  ? a++ : (a ? a++ : a– –), ternary operator is Right to Left associative.

It is of the form expr1 ? expr2 : expr3. Here, expr1 = a– –, expr1 returns 0 (False) and makes a = –1. Thus, we execute expr3. Here, expr3 = a ? a++ : a– –, a is –1 (True), so it executes a++, which returns –1 and makes a = 0.

Therefore, b = –1.

Answer :- B

 

4 Comments

Here, precedence is helping us to put proper parenthesis, precedence doesn't define order of execution.

Precedence and associativity are independent from order of evaluation.

2
2

Yes , this is exactly what I was asking for. Thanks!

the order of execution will depend on that particular operator and how actually the compiler executes it.

is this correct now?

0
0
Yes.
0
0
Answer:

Related questions