Reputation: 3
I have the following code:
#define MIN(a,b) (a <= b ? a : b)
void main()
{
int a = 5;
int* p = &a;
int result = MIN(*p++,12);
printf("%i",result);
}
Theoretically the output should be something smaller than 12, but it turned out giving 34 as its result. So I'm wondering is there something wrong with that inline function or the pointer?
BTW, I meant to have *p++
there rather than (*p)++
. I understand it's gonna increment the address and unbox it.
So another question is normally what could be the value of the next address? In this case, what is the value of *p++
?
Upvotes: 0
Views: 64
Reputation: 213130
This line:
int result = MIN(*p++,12);
expands to:
int result = (*p++ <= 12 ? *p++ : 12);
^^^^ ^^^^
So p
gets incremented twice, and the value returned is garbage (note that this is actually undefined behaviour).
And this is why the use of such macros is strongly discouraged - you really don't want nasty side-effects like this.
Use a proper inline function instead of a macro:
inline int MIN(int a, int b)
{
return a <= b ? a : b;
}
Upvotes: 3