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

won't be the same as:

if (a == b ? 1 : 2)

Solved

Posted on 2004-11-19

hi exeprts.

can anyone pleae give me an example showing the Right to left associativity of ternary operator.

waiting..

thanks.

can anyone pleae give me an example showing the Right to left associativity of ternary operator.

waiting..

thanks.

5 Comments

Right-to-left associativity says this is interpreted as

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

not

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

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_

lot of answers.

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.

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

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

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

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

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

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

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

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

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

produces:

012012212

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

Paul

By clicking you are agreeing to Experts Exchange's Terms of Use.

Title | # Comments | Views | Activity |
---|---|---|---|

C: GetDiskFreeSpaceEx() for default drive | 14 | 92 | |

Need help with functions using strings in C programming. What am I doing wrong here? | 22 | 171 | |

difference between mmap and malloc/valloc + mmap fixed | 18 | 231 | |

sameEnds challenge | 3 | 78 |

Join the community of 500,000 technology professionals and ask your questions.

Connect with top rated Experts

**15** Experts available now in Live!