下面的宏使用_Generic
来确定参数是否为数组(而不是指针):
#include <stdio.h>
#define IS_ARRAY(T) \
_Generic( &(T)[0], \
typeof(T) : 0, \
default : 1 \
)
int a[2];
int *p = a;
int main() {
printf( "IS_ARRAY(a) = %d\n", IS_ARRAY(a) );
printf( "IS_ARRAY(p) = %d\n", IS_ARRAY(p) );
}
以及:
$ clang --version
clang version 17.0.6
$ clang -std=c2x a.c
我得到了:
a.c:15:33: warning: due to lvalue conversion of the controlling expression, association of type 'typeof ((a))' (aka 'int[2]') will never be selected because it is of array type [-Wunreachable-code-generic-assoc]
15 | printf( "IS_ARRAY(a) = %d\n", IS_ARRAY(a) );
| ^
a.c:7:5: note: expanded from macro 'IS_ARRAY'
7 | typeof( (T) ) : 0, \
| ^
1 warning generated.
然而:
$ ./a.out
IS_ARRAY(a) = 1
IS_ARRAY(p) = 0
尽管有警告,但似乎起作用了.这里的警告是错的吗?