Problem in using Macro

Dec 5, 2012 at 7:29pm
#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 :)
Dec 5, 2012 at 7:38pm
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 Dec 5, 2012 at 7:41pm
Dec 5, 2012 at 7:40pm
Oh, thanks!
Dec 5, 2012 at 7:42pm
I edited the post to give a bit more information
Dec 5, 2012 at 7:49pm
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 Dec 5, 2012 at 7:51pm
Topic archived. No new replies allowed.