-1

I have defined a macro to find the square of a number.

#include<iostream>
#define square(x) x*x
using namespace std;
int main()
{
    int a = square(2+3);
    cout<<a<<endl;
}

The output in the above case is 11. I have replaced the expression in the brackets with (3+2) then also the output is 11. Similarly for (4+2) and (2+4) the output is 14.

I have replaced the '+' with '*' then it is giving the normal output like it calculated the expression in the brackets first and calculating the square of that.

Can any one tell me how to generalize the output like what is the order of execution?

MathGeek
  • 511
  • 6
  • 17
  • 5
    The crux of your problem is that C macros aren't executed like functions, the preprocessor basically just uses text replacement on the arguments and lets the parser figure out what it means later. These kinds of bugs are very easy to write and can be very difficult to find and correct. You're likely better off just writing a function. – Willis Hershey Aug 15 '20 at 06:06

1 Answers1

4

With #define square(x) x*x, this square(2+3) turns into

2+3*2+3. Which of course causes unexpected results because of preference of * over +. The problem does not occur with *, because the order of preference in that case does not matter.

You probably want #define square(x) (x)*(x), in order to get (2+3)*(2+3).

Or, less vulnerable to indirect problems of similar nature,

#define square(x) ((x)*(x)), in order to get ((2+3)*(2+3)).

Even better, because macros really offer a lot of traps like this one to get caught in, you should simply use a cleanly defined function. With modern compilers most of the reasons to use macros are obsolete.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • My pleasure. :-) – Yunnosch Aug 15 '20 at 06:05
  • 1
    You seem to be missing the go-to solution: A regular function. – chris Aug 15 '20 at 06:42
  • @chris True. I was focusing on the problem as perceived by Op. But I will mention the function. Thanks for the feedback. (done) – Yunnosch Aug 15 '20 at 07:02
  • I never used macros, I generally use functions. But it is actually a question that was asked to my friend in one of the interview I am preparing for. So I have to tell the value of 'a' if the code is like the one mentioned in the question with macros. – MathGeek Aug 15 '20 at 09:41