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 .
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 .
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.
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++))
.
This is what your code expands out to:
a = (b + 1 * b + 1)
Since *
has more precedence than +
, 1 * b
is evaluated first.