4

Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
Undefined Behavior and Sequence Points (C++ FAQ entry)

In C and C++ how is the expression x+++++y parsed? As x++ ++ +y or as x++ + ++y ?

Community
  • 1
  • 1
rMan
  • 61
  • 3
  • 6
    You're not considering actually writing it, though, right? *Right?* ;-) – T.J. Crowder Dec 10 '10 at 17:33
  • 1
    Entering an obfuscated code competition? – jball Dec 10 '10 at 17:33
  • 2
    @Lucero : This question has no relation with the one that you have added in your comment. – Prasoon Saurav Dec 10 '10 at 17:36
  • 3
    @Lucero: No, that question is about what happens after tokenization, and this is about tokenization. – David Thornley Dec 10 '10 at 17:37
  • 3
    @Lucero: Echoing David, this question is about tokenization and parsing (hence the `parsing` tag). The questions you're finding are about sequence points, which are a totally different thing. (The difference being that `i = i++ + ++i` involves the same variable more than once, introducing sequence point stuff, whereas this question talks about independent variables.) – T.J. Crowder Dec 10 '10 at 17:39

1 Answers1

11

x+++++y is parsed as x ++ ++ + y and not as x ++ + ++ y. According to Maximal Munch principle "the tokenizer should keep reading characters from the source file until adding one more character causes the current token to stop making sense"

x++ ++ +y should not compile(In C and C++) because the post-increment operator ++ requires an lvalue as an argument and returns an rvalue.

Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
  • This is true for all languages which use greedy/longest-match regexes for tokenization - which should be most of them (actually, I can't think of one that doesn't). –  Dec 10 '10 at 17:33
  • *"`x++ ++ +y` should not compile"* And indeed, it doesn't (on `gcc` anyway): `error: lvalue required as increment operand` Wow was I relieved to see that. – T.J. Crowder Dec 10 '10 at 17:37
  • Unfortunately, not all forms of '+++++++++' are uncompilable. MSVC at least happily accepts some of them and then does WTF knows what with it. There's this little, in-house utility of ours that has always been given to an intern to do (not my decision). It's got shit like that in it all over the place. – Edward Strange Dec 10 '10 at 17:51
  • 4
    `x++ ++ +y` will compile if `x` or `y` is of a class type with suitably defined operator overloads. – James McNellis Dec 10 '10 at 18:07
  • 2
    A bit of trivia: the next version of C++ will relax the "maximal munch" rule for ">>" tokens when dealing with template parameters. – Michael Burr Dec 10 '10 at 18:23
  • "According to Maximal Munch principle" -- the world is not composed of only LL grammars, is it? – Gene Bushuyev Dec 10 '10 at 19:21