'typeof'之前的预期表达式或'typeof'之前预期的primary-expression

elh*_*ɥןǝ 3 c macros gcc

我有一个像这样的宏:

#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;
}
Run Code Online (Sandbox Code Playgroud)

在使用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);
  ^
Run Code Online (Sandbox Code Playgroud)

Lou*_*uen 7

我不认为你可以使用typeof来测试类型相等.如果查看gcc手册,typeof (expr)则静态地替换为表达式的类型,这允许您声明变量:

int i;
typeof(&i) p; 
Run Code Online (Sandbox Code Playgroud)

在这种情况下,最后一条指令将等同于 int* p;

但是,如果你typeof在if语句中使用像你的那样会是一个错误,因为它等同于写一些类似的东西

if ( char* == char *)
Run Code Online (Sandbox Code Playgroud)

这导致了错误.