Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 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 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...