Hacker News new | comments | show | ask | jobs | submit login

It also works if you add a space:

    x+ +3;
I always thought the unary plus operator is a complete waste, and shouldn't be implemented. I can't imagine a situation when it's needed.

EDIT: technically, it's a bug in GCC. It sees "x++" and assumes it's a unary increment, followed by a hardcoded 3. It definitely should consider that it's an addition followed by a unary plus (which has higher precedence than addition). But I guess it's an ambiguous syntax, and GCC is just being strict.

This is not a bug in GCC. The compiler is required to interpret this as the syntactically-invalid "y = x ++ 3 ;" by the common so-nicknamed maximal-munch property of lexers for various languages. In the 1998 C++ standard, this is in section 2.4/3:

"If the input stream has been parsed into preprocessing tokens up to a given character, the next preprocessing token is the longest sequence of characters that could constitute a preprocessing token, even if that would cause further lexical analysis to fail."

This is the same reason why (prior to C++11) nested templates have to be written with an excess space: "std::vector<std::list<int> > foo". (C++11 has a lexer hack to allow a >> token to be valid here and equivalent to two > > tokens.)

For this ++ example, if you want the valid parse, you get to put the space in yourself, just like we're used to for nested templates. This is the trade-off for having a fast mostly conceptually-separate lexer.

Unary plus is nice if you want to write out the symmetry in things like "int signum[] = { -1, 0, +1 }" and I expect there are meaningful uses in ensuring desired conversions occur in some overloading situations (though there would of course be a case for being explicit...).


Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact