2

Hello everyone I am having doubt in this code

#include<iostream>
#define SQR(x)(x*x) 

int main() {
    int a, b=3;
    a = SQR(b+1);

    std::cout << a;
}

The result is 7 instead of 16 .I am not able to understand it .

Freedom911
  • 610
  • 2
  • 12
  • 26

3 Answers3

5

The macro expands to a literal

(b + 1 * b + 1)

So your result is:

3 + (1 * 3) + 1.

Change your macro to:

#define SQR(x)((x)*(x))

And it should work.

Serge
  • 1,974
  • 6
  • 21
  • 33
5

After substituting the macro, the code looks like this:

int main() {
    int a, b=3;
    a = b+1*b+1;

    std::cout << a;
}

Which is the same as b+(1*b)+1 with operator precedence. You can fix it by either using a function instead:

inline int SQR(int x) {
    return x*x;
}

Or more generically:

template<class T> inline T SQR(T x) {
    return x*x;
}

Or by surrounding the macro parameters in parentheses:

#define SQR(x) ((x)*(x))

Which would expand to ((b+1)*(b+1)). In general I wouldn't recommend using a macro for this, however, because there are other potential problems, such as SQR(x++) expanding to ((x++)*(x++)).

James M
  • 18,506
  • 3
  • 48
  • 56
1

This is what your code expands out to:

a = (b + 1 * b + 1)

Since * has more precedence than +, 1 * b is evaluated first.

David G
  • 94,763
  • 41
  • 167
  • 253