Can anyone please explain how this works
#define maxMacro(a,b) ( (a) > (b) ) ? (a) : (b)
inline int maxInline(int a, int b)
{
return a > b ? a : b;
}
int main()
{
int i = 1; j = 2, k = 0;
k = maxMacro(i,j++); // now i = 1, j = 4 and k = 3, Why ?? Where is it incremented ?
//reset values
i = 1; j = 2, k = 0;
k = maxInline(i,j++); // now i = 1, j = 3, and k = 2, Why ??
return 0;
}
So, I want to know where exactly is the value of j incremented, while checking condition or while returning or while calling ?
UPDATE : Thanks to all, now I understand this. But just out of curiosity, why would anyone do j++ while calling method, why not increment j after calling method, this way it would be less confusing. I saw this piece of code somewhere so asking it !!
The issue is the preprocessor does just straight text substitution for macros.
maxMacro(i, j++)
becomes
( (i) > (j++) ) ? (i) : (j++)
As you can see, it does two increments when j is greater.
This is exactly why you should prefer inline functions over macros.
k = maxMacro(i,j++);
expands to:
k = ( (i) > (j++) ) ? (i) : (j++)
Because of the sequence point of ?:
the behaviour of this is well defined. When i
is less than the initial value of j
, j
is incremented twice and k receives the once incremented value of j
.
(If i
were greater than the initial value of j
, then j
would be incremented only once when evaluating (i) > (j++)
, k
would be assigned that value of (i)
and the second increment would not be performed.)
In:
k = maxInline(i,j++);
maxInline is called with the values i
and j
before increment (1 and 2), j is incremented before the function call, and k
is assigned the return value of maxInline (2).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With