output of #define

I have a micro defined
 
#define multi(a,b) a*b 


now what would be the output when I say
multi(2+2,3+3) ? My compiler gives output as 11. But I don't understand how it is doing it. Could somebody please explain?

Some random outputs are
multi(1+2,3+5) // 12
multi(4+4,3+3) //19

Not getting the logic behind it :( Thanks in advance.
The preprocessor doesn't care about C++ syntax. When it sees multi(2+2,3+3) it will just replace it with 2+2*3+3.
Last edited on
#define multi(a,b) a*b

multi(2+2,3+3) ==> 2+2*3+3 == 11

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

multi(2+2,3+3) ==> (2+2)*(3+3) == 24
This is reason #63 why you should avoid macros.

use an inline function instead:

 
int multi(int a,int b) { return a*b; }


or if you want to be fancy:

1
2
template<typename T>
T multi(const T& a,const T& b) { return a*b; }
.. if you want to be even more fancy:
1
2
template<typename T1, typename T2>
auto multi(const T1& a,const T2& b) -> decltype(a*b) { return a*b; }
Oops..right. Compiler doesn't care about syntax..How did I miss this thing :( Thanks a lot for help.
(I hate using macros, but this was a question asked to me in interview and I was looking at it like a fool for 10 mins..Wondering what the hell!) :D
Topic archived. No new replies allowed.