3
int x = 2;
int y = 5;

int z = x +++ y;

printf("%d",z);

Both VC++ and GCC give 7 as output. My confusion here is, it could be x++ + y, or x + ++y. Is this defined?

jam
  • 51
  • 4

2 Answers2

7

In both C and C++, the principle of lexical analysis is, the longest sequence of characters that can form a valid token is taken as one (also known as "maximal munch"). So x+++y is unambiguously parsed as (x++) + y.

2.4/(3.3) -- Otherwise, 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.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
  • Whilst the overall answer is correct, I think the paragraph quoted isn't the one relevant in this case, as it is referring to the preprocessor tokenisation, which, whilst generally the same idea, has some subtle differences. – Mats Petersson Feb 21 '15 at 13:36
  • 1
    @MatsPetersson What is this "preprocessor tokenisation" of which you speak? I'm not familiar with the term. Which section of the standard are you alluding to? You seem to misunderstand the translation process, as outlined in "**2.2** Phases of translation." There's only one kind of tokenisation, the one performed in translation phase 3. – Igor Tandetnik Feb 21 '15 at 13:39
  • And to make things even more convenient, `++` precedence is higher than `+`. – Déjà vu Feb 21 '15 at 13:41
  • 1
    @ring0 Would it make a difference in this case if the precedence were the other way around? – juanchopanza Feb 21 '15 at 13:49
  • @juanchopanza Why would that make a difference? (`++` over `+` is a syntactic decision, while precedence is part of semantics). However, having `++` over `+` and precedence "match" does indeed ease the reading - the other way around would be counter intuitive. – Déjà vu Feb 21 '15 at 14:45
6

According to maximal munch rule compiler always interpret x +++ y as x++ + y and therefore behaviour is well defined.

C11: 6.4 Lexical elements:

p(4)

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.[...]

p(6)

EXAMPLE 2 The program fragment x+++++y is parsed as x ++ ++ + y, which violates a constraint on increment operators, even though the parse x ++ + ++ y might yield a correct expression.

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264