Problem in using Macro

#define sqrt(x) x*x

sqrt(2-5);

Can anybody tell me that why the above statement results -13 instead of 9 ?
I wanna know how this statement works actually.
Thanks in advance :)
because x = 2-5
so x*x = 2-5 *2-5

and
2-5 * 2-5 = 2-10-5 = -8-5 = -13

which is why macros like this have the values surrounded by brackets.
#define sqrt(x) (x)*(x)
which would give
(2-5) * (2-5)
= -3 *-3 = 9


Also
why would anyone try to find the square root of a nymber by
multiplying it by itself (because that creates the square of the number not the square root).
Last edited on
Oh, thanks!
I edited the post to give a bit more information
Classic pitfall of C.
Just remember, the preprocessor works like an automatic copy-paster.
In your case, every occurrence of the sqrt() macro will be replaced by its definition, updated with the parameters.

One solution is to use parentheses, like guestgulkan already explained.
Another is to use an inline function, or a template function.
Last edited on
Topic archived. No new replies allowed.