Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
702 views
in Technique[技术] by (71.8m points)

understanding a C Preprocessor Macro's output vs a line code

#define AD(x,y) (x+y)
int main()
{
    int x1=5,y1=2,z1;
    int x2=5,y2=2,z2;
    z1 = AD(x1,++y1);
    z2 = (x2+++y2) ;
    printf("%d %d %d
",x1,y1,z1);
    printf("%d %d %d
",x2,y2,z2);
}

why the output is different? the first case is : 5 3 8 and the second is : 6 2 7

question from:https://stackoverflow.com/questions/65907318/understanding-a-c-preprocessor-macros-output-vs-a-line-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This expression

z2=x2+++y2;

is parsed by the compiler like

z2 = x2++ + y2;

From the C Standard (6.4 Lexical elements)

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.

So these tokens +++ are parsed like ++ and +. The expression with the macro

z1=AD(x1,++y1);

is parsed by the compiler like

z1 = x1 + ++y1;

The compiler already formed these sets of tokens x1 and ++y1 due to the comma between the tokens.

So these two statements are different.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...