Search code examples
c++inlinec-preprocessorcallbynamecall-by-value

Call by Name/Call by Value


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?


Solution

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