I have some code dispatching a function based on the type of its argument, using the _Generic. I do not understand the warning gcc generates.
Compile with gcc main.c
#include <stdio.h>
#define FOOBAR(x) _Generic((x), \
int *: foo(x), \
long *: bar(x) \
)
void foo(int* x) {
printf("foo\n");
}
void bar(long* y) {
printf("bar\n");
}
int main() {
int a = 1111;
long b = 2222;
FOOBAR(&a);
FOOBAR(&b);
}
Now, this code does compile and _Generic works as expected, i.e. "foo" appears then "bar". However, the compiler (gcc and clang) generate a weird warning that looks like its matching the argument against _Generic to the wrong line:
main.c: In function ‘main’:
main.c:20:12: warning: passing argument 1 of ‘bar’ from incompatible pointer type [-Wincompatible-pointer-types]
20 | FOOBAR(&a);
| ^~
| |
| int *
main.c:5:15: note: in definition of macro ‘FOOBAR’
5 | long *: bar(x) \
| ^
main.c:12:16: note: expected ‘long int *’ but argument is of type ‘int *’
12 | void bar(long* y) {
| ~~~~~~^
main.c:21:12: warning: passing argument 1 of ‘foo’ from incompatible pointer type [-Wincompatible-pointer-types]
21 | FOOBAR(&b);
| ^~
| |
| long int *
main.c:4:14: note: in definition of macro ‘FOOBAR’
4 | int *: foo(x), \
| ^
main.c:8:15: note: expected ‘int *’ but argument is of type ‘long int *’
8 | void foo(int* x) {
| ~~~~~^
Two warnings are generated, one for each FOOBAR. It appears to be passing &a
which is int * to bar which takes a long *, and vice versa for &b
.
(Comment out the one of the FOOBARs to see just one incompatible pointer error.)
Why is gcc warning me that _Generic is dispatching its arg to the wrong function?
I know this isn't normally how people use _Generic, i.e. the argument list would usually be outside the _Generic(). But I have some use cases for dispatching to functions that take different number of arguments.