【问题标题】:Initializing C arrays with __auto_type使用 __auto_type 初始化 C 数组
【发布时间】:2021-08-15 14:30:01
【问题描述】:

我尝试在 GNU C 中使用 __auto_type 初始化一个数组,但这似乎是一个语法错误:

#include <stdio.h>

int main() {
   __auto_type a[] = {1,2,3,4};
   printf("%d",a[0]);
   return 0;
}

作为一种解决方法,我可以定义一个可变参数宏来使用typeof 初始化数组,但这更麻烦:

#include <stdio.h>

#define infer_array_type(a,b,...) typeof(b) a[] = {b,__VA_ARGS__}

int main() {
   infer_array_type(a,1,2,3,4);
   printf("%d",a[0]);
   return 0;
}

难道不能在 GNU C 中使用 __auto_type 而不是 typeof 来初始化数组吗?

【问题讨论】:

  • docu 声明 the declaration must declare only one variable, whose declarator must just be an identifier, the declaration must be initialized, and the type of the variable is determined by the initializer 错误消息显示 '__auto_type' requires a plain identifier as declarator 这不是回答您的问题吗?

标签: gcc type-inference


【解决方案1】:

在 GNU C 中,可以定义一个返回数组的statement expression,因此可以使用__auto_type 来初始化数组:

#include <stdio.h>

#define infer_array_type(b,...) ({typeof(b) a[] = {b,__VA_ARGS__}; a;})

int main() {
   __auto_type a = infer_array_type(1,2,3,4);
   printf("%d",a[0]);
   return 0;
}

【讨论】:

    猜你喜欢
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 2018-01-15
    • 2013-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多