Please note that although the macro
#define Square(x) ((x)*(x))
seems to solve the problem, it does not. Consider this:
int x = 5;
printf("%d\n", Square(x++));
The preprocessor expands this to:
((x++)*(x++))
which is undefined behavior. Some compilers will evaluate this as
(5 * 5)
which seems as expected in the first place. But x = 7
afterwards, since the increment operator has been applied twice. Clearly not what you were looking for.
For the output, see here: http://ideone.com/9xwyaP
This is why macros* are evil.
(*Macros which tend to be used as a replacement for inline-functions.)
You can fix this in C++ using template functions which can handle all types and in C by specifying a concrete type (since even overloading isn't supported in C, the best you can get is different functions with suffixes):
// C
int SquareI(int x) { return x * x; }
float SquareF(float x) { return x * x; }
double SquareD(double x) { return x * x; }
// C++
template<typename T>
T Square(T x) { return x * x; }
Specifically for GCC, there is another solution, since GCC provides the typeof
operator so we can introduce a temporary value within the macro:
#define Square(x) ({ typeof (x) _x = (x); _x * _x; })
Et voila: http://ideone.com/OGu08W