Skip to content

Design note: Postfix unary operators vs binary operators

Herb Sutter edited this page Mar 21, 2024 · 7 revisions

Q: Does postfix unary * and & conflict with binary * and &, for example a**b?

A: Yes, and it's disambiguated

There is a tension between two things:

  • most unary operators including * and & naturally want to be postfix (see Design note: Postfix operators), and
  • we want to support all Cpp1 operators in order to ensure great compatibility with all existing C++ libraries including those that overload all the possible operators (e.g., expression templates) but that includes binary * and &

So if we want to have both, we have a few choices, including:

  • Change the syntax of pointers/dereference to use something that is not a binary operator. For example, a lot of people would suggest one of the very few unused symbols, notably @. But note that we only ever get to take each one of those once, ever, in all the history of time, so we should have a truly break-the-glass no-other-option reason to take it. This doesn't rise to that bar.
  • Change the syntax of pointers/dereference to use another operator that has a binary form we can ban. Here the notable and obvious example is ^, and in Cpp2 for a while I actually used ^ for pointers/deference and banned the bitwise binary operators and required programmers to write bitxor et al. instead, which is arguably more readable (and the slightly longer spelling highlights an important operation, and they're already alternative tokens, and there are already std:: versions, and other rationale/rationalizations). But the moment I tried converting spdlog to Cpp2 syntax by hand a year ago, I found myself having to convert a lot of those, and after the first dozen I realized that banning the bitwise binary operators was a nontrivial impediment to the more important goal of making converting code to Cpp2 as friction-free as possible.
  • Disambiguate unary and binary * and &. This is what I'm currently trying... the current rule is that if can be a postfix operator, it is: * and & are binary operators if followed by ( or an identifier or a literal.