-4

Dear(s) I have the following code of C that give me the answer = 11 correct but I cannot pick the point over here. Kindly explain if any have the key.

include

using namespace std;

int main()
{
    #define square(x) x*x
    cout<<square(3+2);
    return 0;
}
Community
  • 1
  • 1
Raham
  • 4,781
  • 3
  • 24
  • 27

1 Answers1

5

square(3+2) expands into 3+2*3+2, which evaluates as 3 + (2 * 3) + 2.

#define square(x) ((x) * (x)) should do what you want.

(The inner parentheses solve the problem you presented, the outer parentheses solve the problem you haven't found yet :P In fact, make it SQUARE, just in case, for yet another issue. Read TruthSeeker's link for details.)

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • [`std::pow(3+2, 2)`](https://en.cppreference.com/w/cpp/numeric/math/pow) also does what he wants. Always use the standard stuff. – nada Dec 10 '19 at 09:16
  • @nada: `std::pow` has no `int` version, and does a lot more processing than `x * x`. – Amadan Dec 10 '19 at 09:18
  • You're suggesting premature optimization and use of macros over code readability and using the C++ standard library? – nada Dec 10 '19 at 09:19
  • @nada `x * x` _is_ standard stuff. And I don't particularly consider `pow(x, 2)` more readable. _shrug_ Finally, `pow(x, 2)` does not answer this particular question (why the result is 11). Also, I don't see it as a micro-optimisation when it changes literally only one line. If you argued for an inline function over macro, all good; but using `pow` for integral square is not avoiding premature optimisation, but being a wanton wastrel. – Amadan Dec 10 '19 at 09:36
  • 1
    Thanks for elaborating your pov _wink_. Inline function sounds good. After all, macros are the reason why OP had to come here in the first place. – nada Dec 10 '19 at 09:59