1

There is the next code:

#include <iostream>
#define F(x) (2*x*x)
using namespace std;

int main()
{
    int a = 1, b = 2;
    int res = F(a + b);
}   

The res value is 6, but why is it?

Anton Golovenko
  • 634
  • 4
  • 19

2 Answers2

3

Macros are used to replace the text. This is what ht code is doing:

2*x*x

replacing x with (a+b) 2*a+b*a+b

a = 1 b = 2

Answer is 6

Abhishek Dutt
  • 1,308
  • 7
  • 14
  • 24
0

The #define directive simply replace the parameter in the macro. So in your code:

F(a + b) turns into 2*a + b*a + b which is 2*1+2*1+2 that is equal to 6.

I suggest to use inline functions for this matter, but if you really want to use a macro (which is highly unrecommended for cases like these for many reasons) surround each parameter with brackets.

Example: #define F(x) (2*(x)*(x))

Roy Avidan
  • 769
  • 8
  • 25