c - 'typeof' 之前的预期表达式或 'typeof' 之前的预期主表达式

标签 c gcc macros

我有一个这样的宏:

#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/

相关文章:

c - gcc:汇编代码中不同引用的命令行参数

perl - 配置 Perl::Tidy 来处理自定义关键字

visual-c++ - %(AdditionalIncludeDirectories) 含义

C 程序两个日期之间的天数——输出稍微太高?

c - 根据 C 标准,负整数文字是解释为单个文字,还是运算符和文字?

c - 数字的乘积,未打印正确的数字

c - 需要帮助编译一些东西! ( :

c++ - gcc 中的模板显式实例化(定义和声明)

c - SDL 窗口未正确打开

testing - iMacros 很好但不可靠。还有其他选择吗?