Search code examples
c++cmacrosexecution

What is the order of execution in these type of cases?


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?


Solution

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