Sunandani Boddula
Sunandani Boddula

Reputation: 9

What could be the working of the statement with conditional operator?

#include<stdio.h>
void main()

{

        int x=2,y=0;

        int z= (y++) ? y==1 &&x:0;

        printf("%d\n",z);

}

How does the compiler take the statement int z= (y++) ? y==1 &&x:0;

Upvotes: 0

Views: 121

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140148

in:

int z= (y++) ? y==1 &&x:0;

y is evaluated then incremented. Since the original value is 0, you're getting the "else" part of the ternary so z is 0.

Change to (++y) then you enter the "if" part of the ternary, and since y==1 and x is not 0, z takes the value 1

In that case it's guaranteed that y==1. It works with specified behavior because of the sequence point the ternary expression materializes, so the pre-incrementation has to have been performed.

Sequence points ...

Between the evaluations of the first operand of the conditional ? : operator and whichever of the second and third operands is evaluated

Such subtle and cryptic changes makes that code hardly maintainable. Don't do this at home.

Upvotes: 3

Related Questions