• C

# associtiavity of ternary operator

hi exeprts.
can anyone pleae give me an example showing the Right to left associativity of ternary operator.
waiting..
thanks.
###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Software ArchitectCommented:
Here is a case you can analyze:

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

won't be the same as:

if (a == b ? 1 : 2)
0
Commented:
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
Commented:
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 Commented:
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
Commented:
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

Experts Exchange Solution brought to you by

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.