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

c - Why is "i" variable getting incremented twice in my program?

One of my friend showed me this program and asked me why is i variable getting incremented twice.

According to my understanding MAX(i++, ++j); in this line i is first send as a parameter and then incremented, so if the initial value of i is 10 then the incremented value should be 11, but it shows the incremented value of i as 12.

Program :

#include<stdio.h>

#define MAX(x,y) (x)>(y)?(x):(y)

void main(void)
{
    int i = 10;
    int j = 5;
    int k = 0;

    k = MAX(i++, ++j);

    printf("%d %d %d",i,j,k);
}

Output :

12 6 11

Can someone please explain me how is the value incremented to 12 ?

Thanks.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

MAX is a macro, not a function. In your use case, it expands to:

k = (i++) > (++j) ? (i++) : (++j);

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

...