【发布时间】:2016-07-26 13:18:09
【问题描述】:
我有一个这样的宏:
#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不是标准 C,它是 GCC 中的 GNU extension。你用的是什么编译器? -
我正在使用 gcc 编译器
-
代码必须采用
e的 SWAG。它没有办法知道,typeof也没有。 -
typeof不产生值,它产生一个类型。您无法比较类型。例如if (int == int)是无效的比较。 -
摇摆的野驴猜......