Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is i+++j always treated as i++ + j? [duplicate]

Tags:

c

operators

In the printf statement i+++j, is it always treated as i++ +j?

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main() {
    int i =5,j= 6, z;
    z=i^j;
    printf("%d",i+++j);
    return 0;
}
like image 260
user2713461 Avatar asked Sep 01 '13 17:09

user2713461


2 Answers

i+++j is equivalent to i++ + j.

This has nothing to do with operator precedence. The +++ is resolved to ++ + by the compiler before expressions are parsed.

The C standard defines a sequence of translation phases, each using as its input the output of the previous one. +++ is resolved to ++ + in phase 3, which decomposes the source into preprocessor tokens. Operator precedence is not considered until phase 7, syntactic and semantic analysis. (The translation phases don't have to be implemented as distinct phases or passes, but the compiler must behave as if they are.)

The rules that says +++ is resolved to ++ + and not + ++ is what's informally called the "maximal munch rule". It's stated in section 6.4 paragraph 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.

(Amusingly, the index refers to "maximal munch", but that term isn't mentioned anywhere else in the standard.)

This also implies that i+++++j, which could be tokenized as the valid expression i++ + ++j, is actually i ++ ++ + j, which is a syntax error.

Of course the solution, for a programmer, is to add whitespace to make the division into tokens clear: i++ + j. (i+++j is perfectly clear to the compiler, but i++ + j is much clearer to a human reader.)

Reference: N1570, section 6.4, paragraph 4. N1570 is a draft of the 2011 ISO C standard. This rule is unchanged from earlier versions of the standard. Translation phases are discussed

like image 83
Keith Thompson Avatar answered Oct 06 '22 07:10

Keith Thompson


Yes. It will be parsed as (i++) + (j).

like image 37
haccks Avatar answered Oct 06 '22 05:10

haccks