Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type-generic programming with macros: tricks to determine type?

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?

like image 907
R.. GitHub STOP HELPING ICE Avatar asked Dec 02 '10 03:12

R.. GitHub STOP HELPING ICE


1 Answers

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.

like image 175
Karl Knechtel Avatar answered Oct 25 '22 02:10

Karl Knechtel