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
401 views
in Technique[技术] by (71.8m points)

How to determine i+++--j in C

In C,

int i = 20;
int j = 5;
int k = i+++--j;

Why is k=24?

In my understanding, k = (i)++ + (--j) so it is (20 + 4)++ = 25.

OK. Here is a little programme I wrote for test, and yes the post increment is done after k is assigned.

#include <stdio.h>
int main()
{
    int i = 20;
    int k = i++;
    printf("%d
", k);
    printf("%d
", i);
    return 0;
}

Output:

20
21

Could anyone tell me why vote down? I was unsure about this because I was a new commer to C.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

C has a famous rule of maximal munch strategy. From this rule:

i+++--j

is parsed as

(i++) + (--j) 

(C99, 6.4p4) "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."

And of course the value of i++ is i and the value of --j is j - 1, so the value of i+++--j is 20 + 4 equal to 24.


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

...