2

I'm trying to understand this block of code here:

#include <iostream>
using namespace std;

#define mymult(a, b) a*b
inline int mymult1(int a, int b) {return a*b;}

int main() {
cout << "mymult(2+2, 3+3) = " << mymult(2+2, 3+3) << "\n";
cout << "mymult1(2+2, 3+3) = " << mymult1(2+2, 3+3) << "\n";
}

mymult = 11, and mymult1 = 24. I know that '#define's essentially work via call by name, rather than call by value. However, I'm having trouble understanding why the value it returns is 11... and not 24. What causes this?

8
  • 7
    #define is bacisally name substition, so it transforms into 2+2*3+3
    – Predelnik
    Apr 2, 2015 at 19:00
  • @predlnik that is the answer!!
    – Steephen
    Apr 2, 2015 at 19:03
  • ...which is one of many reasons to prefer inline functions over macros. Apr 2, 2015 at 19:04
  • ... and when using macros to pass each argument within parantheses.
    – cadaniluk
    Apr 2, 2015 at 19:05
  • ... unless you wish to succeed in obfuscated C-contest....
    – BitTickler
    Apr 2, 2015 at 19:07

1 Answer 1

6

Option 1: In the case of:

#define mymult(a, b) a*b

a and b are treated like place holder strings and when you call mymult, the parameters a and b are just copied as they were written. In other words:

mymult(2+2, 3+3) = 2+2*3+3

where a = 2+2, b = 3+3.

Therefore you may call mymult as follows:

mymult( (2+2), (3+3) )

where a = (2+2), b = (3+3).

This will be interpreted as:

mymult( (2+2), (3+3) ) = (2+2)*(3+3)    

and return the value of 24 as expected.

Option 2: If we are allowed to modify the #define statement then an alternative way of doing this is defining it with the parentheses as follows:

#define mymult(a, b) (a)*(b)

This will give the same expected result since a and b will be put directly into the parentheses as they are. In other words:

mymult(2+2, 3+3) = (2+2)*(3+3) = 24

where a = 2+2, b = 3+3.

Option 3: Stick with the inline function as defined in OP:

inline int mymult(int a, int b) {return a*b;}

Good luck!

3
  • 4
    Or #define mymult(a, b) (a)*(b)
    – LogicStuff
    Apr 2, 2015 at 19:10
  • 2
    A better fix is to change how mymult is defined. #define mymult(a, b) (a)*(b).
    – R Sahu
    Apr 2, 2015 at 19:11
  • @LogicStuff and @R Sahu : If you are allowed to modify the macro, then yes your suggestion makes more sense. Even, ultimately an inline function is preferable over macro in that particular case. Apr 2, 2015 at 19:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.