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;
}
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
Yes. It will be parsed as (i++) + (j)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With