简体   繁体   中英

Increment (++) a dereferenced pointer in a macro --> result is +2 instead of +1

I have the following code:

#include <stdio.h>

#define MIN(x, y) ((x) <= (y) ? (x) : (y))

int main ()
{
int x=5, y=0, least;
int *p;
p = &y;
least = MIN((*p)++, x);
printf("y=%d", y);
printf("\nleast=%d", least);
return 0;
}

I would expect the following result: y=1 least=1 but instead y=2 . Can somebody explain why y is now 2 and not 1 . I suppose that it is because some double incrementation, but I do not understand the mechanism behind it. Thanks.

Preprocessor macros work by text substitution. So your line:

least = MIN((*p)++, x);

gets expanded to

least = (((*p)++) <= (x) ? ((*p)++) : (x));

The double-increment is clear.

It's because you are using a macro. Since you are passing the dereferenced pointer plus the increment through the macro, the macro then puts the dereferenced pointer and the increment operation in each place y shows up in your macro. Since y shows up twice in your macro, the increment operator happens two times.

If you do the increment before you call the macro y should only be 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM