TITLE: conditionals and precedence (Newsgroups: comp.std.c++, 17 Feb 99) BURSIAN: Achim Bursian <36C93553.97689C0C@erlf.siemens.de> [snip] >> I have to maintain some code which contains the bad line >> i==0 ? i=1 : i=0; >> Ok, let us not argue that this is bad, bad style. What the programmer >> wanted to express seems to be i ? 0 : 1; >> But I have this line in the code, and my two compilers produce DIFFERENT >> output from it: MCCULLOCH: "Ian McCulloch" > One possibility is that cfront is interpreting the statement as > > (i == 0 ? i = 1 : i ) = 0; > > That is, the left side of the expression returns either i, or i after > being assigned the value 1. The right hand side of the expression > sets the left side (ie i) to 0. > > However, according to C++ PL 3rd ed, assignment has a higher precedence > than?:, so (unless there is a bug in cfront!) that is not what the > compiler is doing. CLAMAGE: Steve Clamage In fact, the language definition has changed over time in the interpretation of such expressions. Originally, C++ followed the C syntax rule: conditional_expression: logical_or_expression logical_or_expression ? expression : conditional_expression But C++ now has this syntax rule instead: conditional_expression: logical_or_expression logical_or_expression ? expression : assignment_expression Also changed is the interpretation of the result. Now, if both legs of the conditional_expression are lvalues, the result is also an lvalue. You can now write b ? x : y = z which will be interpreted the same as this version: *(b ? &x : &y) = z Under the old rules, it would have been interpreted as b ? x : (y=z) Evidently your two compilers don't implement the same version of the rules for conditional expressions.