Namespaces
Variants
Views
Actions

Talk:cpp/language/operator precedence

From cppreference.com

I just changed the operator precedence for ?: to reflect the fact that it's the same precedence as assignment. To see that this is actually true, use a compiler of your choice, and evaluate the following piece of code:

int a = 0, b = 0; true ? a : b = 7;

After that, both a and b are zero, because due to right-to-left associativity (and equal precedence), the compiler sees it as (true ? a : (b = 7)), and will simply evaluate the a branch. If ?: was actually higher precedence than =, the value of a should be 7. Add parentheses to verify. Yes. It is surprising that essentially all precedence tables for C/C++/Java are wrong.

24.5.77.206 15:19, 10 September 2012 (PDT)

Indeed, the grammar reference of the C++ standard lists the assignment and conditional operators as having the same precedence. Thanks for noticing. -- P12 15:41, 10 September 2012 (PDT)
Good exposition of this corner of the grammar: http://stackoverflow.com/a/13515505/273767 --Cubbi (talk) 14:30, 27 December 2013 (PST)

[edit] A simpler version

A link to http://cpp.operator-precedence.com was added to this page, presumably with the idea that it would be useful to have a simpler view of this chart. I've tentatively reverted the change, just to make sure it's not linkbait. Is such a link useful? Alternatively, could this chart be made clearer or simpler? One possibility might be to use color to help convey information. -Nate 00:45, 3 November 2012 (PDT)

The current table gives more information and is more readable than the one at operator-precedence.com.
The colors they chose to categorize the operators are hardly distinguishable, using brighter colors would make the page look very messy.
--Bazzy 04:22, 3 November 2012 (PDT)
I have the same opinion. P12 05:05, 3 November 2012 (PDT)

[edit] Precedence of throw

Is there a reason for throw to have lower precedence than assignment and conditional? Looking at the grammar, this doesn't seem to be the case. Also, if this were true, false ? 7 : throw 3; should be parsed as (false ? 7 : throw) 3; (throw by itself is a valid throw-expression), which would be a syntax error. However, all compilers that I tested parse it as false ? 7 : (throw 3);, which is consistent with conditional and throw having the same precedence and grouping right-to-left. --bogdan (talk) 11:23, 9 May 2015 (PDT)

interesting point.. you might be right. The grammar (A.4[gram.expr]) says
assignment-expression:
      conditional-expression
      logical-or-expression assignment-operator initializer-clause
      throw-expression

meaning one level above comma are all three of ?:, compound assignments, and throw. It's been that way all the way back to 1998. Good job finding a bug in probably the most visited page! --Cubbi (talk) 13:14, 9 May 2015 (PDT)