Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C, C++ preprocessor macro

Tags:

c++

c

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 ?

  • a. using macro
  • b. using inline method

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 !!

like image 298
seg.server.fault Avatar asked Nov 26 '22 22:11

seg.server.fault


2 Answers

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.

like image 59
Michael Avatar answered Nov 29 '22 11:11

Michael


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

like image 37
CB Bailey Avatar answered Nov 29 '22 13:11

CB Bailey