Solved

# associtiavity of ternary operator

Posted on 2004-11-19
Medium Priority
234 Views
hi exeprts.
can anyone pleae give me an example showing the Right to left associativity of ternary operator.
waiting..
thanks.
0
Question by:Gupi

LVL 55

Expert Comment

ID: 12625571
Here is a case you can analyze:

if ((a==b) ? 1 : 2)

won't be the same as:

if (a == b ? 1 : 2)
0

LVL 15

Expert Comment

ID: 12626417
a ? b : c ? d : e;

Right-to-left associativity says this is interpreted as

a ? b : (c ? d : e);

not

(a ? b : c) ? d : e;
0

LVL 3

Expert Comment

ID: 12627665
Jaime:

Those 2 expressions evaluate the same...

== has a higher precedence than ?:, and so it evaluates first regardless of parentheses.

but

a == b ? 0 : 1

and

a == ( b ? 0 : 1 )

are different (since the parentheses force b ? 0 : 1 to be evaluated before ==)

baboo_
0

Author Comment

ID: 12652407
hi. thanks all.
but i am actually interested in an example where
a ? b : c ? d : e;
if intrepreted as  a ? b : (c ? d : e);
will give different answer than if interpreted as  (a ? b : c) ? d : e;

just like 100/20/2 will give different ans if implemented as 100/(20/2) or (100/20) /2

waiting for a good easy to understand example.
Thanks.
0

LVL 16

Accepted Solution

PaulCaswell earned 500 total points
ID: 12653706
What do you want in the example? You've given a good one yourself with a ? b : c ? d : e;

x = 0; printf("%d",x==0?0:x==1?1:2);
x = 1; printf("%d",x==0?0:x==1?1:2);
x = 2; printf("%d",x==0?0:x==1?1:2);

x = 0; printf("%d",x==0?0:(x==1?1:2));
x = 1; printf("%d",x==0?0:(x==1?1:2));
x = 2; printf("%d",x==0?0:(x==1?1:2));

x = 0; printf("%d",(x==0?0:x==1)?1:2);
x = 1; printf("%d",(x==0?0:x==1)?1:2);
x = 2; printf("%d",(x==0?0:x==1)?1:2);

produces:

012012212

showing that the first set is functionally the same as the second and therefore the third is the non-default option.

Paul
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
###### Suggested Courses
Course of the Month13 days, 18 hours left to enroll