我有一个这样的宏:
#include <stdio.h>
#include <stddef.h>
#define m_test_type(e) \
do { \
if (typeof(e) == typeof(char [])) { \
printf("type is char []\n"); \
} else \
if (typeof(e) == typeof(int)) { \
printf("type is int\n"); \
} else { \
printf("type is unknown\n"); \
} \
} while (0)
int main() {
char s[] = "hello";
m_test_type(s);
return 0;
}
在使用 gcc 编译期间出现以下错误:
prog.cpp: In function 'int main()':
prog.cpp:6:14: error: expected primary-expression before 'typeof'
if (typeof(e) == typeof(char *)) { \
^
prog.cpp:19:2: note: in expansion of macro 'm_test_type'
m_test_type(s);
^
prog.cpp:6:14: error: expected ')' before 'typeof'
if (typeof(e) == typeof(char *)) { \
^
prog.cpp:19:2: note: in expansion of macro 'm_test_type'
m_test_type(s);
^
prog.cpp:9:14: error: expected primary-expression before 'typeof'
if (typeof(e) == typeof(int)) { \
^
prog.cpp:19:2: note: in expansion of macro 'm_test_type'
m_test_type(s);
^
prog.cpp:9:14: error: expected ')' before 'typeof'
if (typeof(e) == typeof(int)) { \
^
prog.cpp:19:2: note: in expansion of macro 'm_test_type'
m_test_type(s);
^
最佳答案
我认为您不能使用 typeof 来测试类型是否相等。如果您查看 gcc manual , typeof (expr)
被静态替换为表达式的类型,它允许你声明变量:
int i;
typeof(&i) p;
在这种情况下,最后一条指令将等同于 int* p;
然而,如果你在像你这样的 if 语句中使用 typeof
将是一个错误,因为它等同于编写类似
if ( char* == char *)
导致错误的原因。
关于c - 'typeof' 之前的预期表达式或 'typeof' 之前的预期主表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36446016/