Paul Würtz
Paul Würtz

Reputation: 1771

Using the _Generic macro in C11 fails

I tried to overload a function with the C11 _Generic macro like this:

int isPrim_int   (int num);  
int isPrim_lint  (long int num);  
int isPrim_llint (long long int num);

#define isPrim(_1, ...) _Generic((_1),                              \
                          int:              isPrim_int,             \
                          long int:         isPrim_lint,            \
                          long long int:    isPrim_llint)

But for some reason using isPrim() returns always 1, when using the specific three functions isPrim_int, isPrim_lint and isPrim_llint it works as intended. Any clues whats wrong with my use of the macro?

Thanks a lot!

Upvotes: 4

Views: 300

Answers (1)

AnT stands with Russia
AnT stands with Russia

Reputation: 320531

You "forgot" to post the calling code, but my crystal ball is telling me that most likely you are "selecting" a function, but never actually calling it. Your current _Generic simply evaluates to a function pointer, which is later interpreted as "true" in boolean context.

Apply the () operator to the result of your _Generic expression to actually call the function. E.g.

#define isPrim(_1, ...) _Generic((_1),                              \
                          int:              isPrim_int,             \
                          long int:         isPrim_lint,            \
                          long long int:    isPrim_llint)(_1)

Your original version will also work, but you'd have to use it as follows

int a = 42;
if (isPrim(a)(a))
   ...

which is probably not how you intended it to be used.

Upvotes: 3

Related Questions