5

在 printf 语句中i+++j,它是否总是被视为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;
}
4

3 回答 3

19

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

于 2013-09-01T19:16:52.747 回答
1

是的。它将被解析为(i++) + (j).

于 2013-09-01T17:18:51.450 回答
-2

由于后缀递增/递减运算符的优先级高于加法运算符,因此毫无疑问它将被视为 (i++) + j。因此,这不是编译器问题,您应该考虑运算符优先级图表。

另外,我建议您在表达式之间放置适当的空格,以防您稍后查看代码。:)

希望有帮助!

于 2013-09-01T17:29:29.367 回答