It's possible to do certain types of type-generic-functions as macros in C, for instance things like:
#define SQRT(x) (sizeof(x) == sizeof(float) ? sqrtf((x)) : \
sizeof(x) == sizeof(double) ? sqrt((x)) : \
sqrtl((x)) )
This works (mostly) as expected as long as x
is a floating point type.
But what if I want a type-generic macro that can take either an integer type or a pointer type, which might have the same size. Is there a clever way to test whether the macro argument is an integer or a pointer? What about an integer versus a floating point type?
No. Macros do not know what types are. They perform a literal copy-and-paste of the #define. Type safety simply doesn't exist here.
C is not a strongly typed language in any meaningful sense. If you want some modicum of type safety, use C++, where you can accomplish a little with templates and function overloading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With