-4
#include <iostream>
using namespace std;

#define squareOf(x) x*x

int main() {
// your code goes here
int x;
cout<<squareOf(x+4);
return 0;
}

I thought the answer would come as 16 but it came out as 4. I am confused how does this works.

1 Answers1

8

16 would never be the result here. Let's say you would have initialized x with 0, then you would have your x+4 replaced by x+4*x+4 which would evaluate as 0+4*0+4 = 4.

Preprocessor macros replace source code, they are not functions.

You might now think that maybe

#define squareOf(x) (x)*(x)

would be better, but consider that then

int x = 2;
int y = squareOf(x++);

would result in y = (2)*(3) = 6, not in 4.

If you do not have a really good reason, avoid preprocessor macros. There are good reasons, but if something behaves like a function, better make it a function.

Now take a look at this:

template <class T>
inline T squareOf(const T& number)
{
    return number*number;
}

As inline, it does also replace code (at least if the compiler wants so), but here, this one actually behaves like a function (since it is one). Wouldn't expect a bad outcome from that one.

Aziuth
  • 3,652
  • 3
  • 18
  • 36