Can the following macro bring problems?
#define sq(x) x*x
If yes, then how and why?please help.
As pointed out, you should wrap each use of the argument in parentheses to ensure correct behavior, for example, when the argument is something like i * 2
:
#define sq(x) ((x)*(x))
But there is another potential issue. Consider the following:
result = sq(++i);
This is translated to:
result = ((++i)*(++i))
Where as the intention was likely to increment i
only once, it gets incremented twice. This is a common side effect for macros.
One approach is just to be aware of this when calling it, but a better one is to put sq()
in its own inline function.