Rakesh Sharma
Rakesh Sharma

Reputation: 39

unable to get the output of ternary operator

Code

#include<stdio.h>
main()
{
    int big, x = 3, y = 2, z = 1, q = 4;

    big = (x > y
        ? (z > x ? 20 : 10 && x > y ? 85 : 12)
        : (y > z ? 40 : 10 || x < q ? 30 : 10)
    );

    printf("\nbig =%d", big);
    //getch();
}

Ouput is 85 But Iam not sure how it's working Help me to understand it..

Upvotes: 0

Views: 70

Answers (1)

haccks
haccks

Reputation: 106012

&& has higher precedence than ?:.

big=(x>y?(z>x?20:10 && x>y?85:12): (y>z?40:10 || x<q?30:10));` 

will be parsed as

big=(x>y?(z>x ? 20: ( (10 && x>y) ?85:12) ): (y>z ? 40: (10 || x<q?30:10)));

Since x is greater than y, so 20: (10 && x>y?85:12) will be executed. Both 10 and x > y will be evaluated to true, (10 && x>y) ?85:12) will give 85.

Upvotes: 2

Related Questions