【问题标题】:Why doesn't compound literals assignment work without a typecast为什么没有类型转换就不能进行复合文字赋值
【发布时间】:2014-10-25 13:14:15
【问题描述】:

我对 C 中的文字有疑问。

int a;
//a is an integer that is assigned an integer literal 414
a = 414;

float b;
//b is a float that is assigned a float literal of 3.14
b = 3.14;

struct point {
    int x,y;
};

struct point b;
//{5,6} is a compound literal that is assigned to a struture.
b = {5,6}; //doesn't work.

b = (struct point){5,6}; //works.

如果没有类型转换,这似乎行不通?这是什么原因?

【问题讨论】:

    标签: c c99 compound-literals


    【解决方案1】:

    (struct point){5,6} 整体是一个复合字面量。

    C11 §6.5.2.5 复合文字

    一个后缀表达式,由带括号的类型名称后跟一个大括号组成 初始化器列表是一个复合文字。

    【讨论】:

    • 既然可以在初始化之前从b点的declaration中推断出类型,为什么不起作用?
    • @liv2hak (struct point) 不是演员表,它是复合文字的一部分。
    • 不能从符号表中推断出来吗?
    • @liv2hak:无法推断。 {5,6} 可以是 int[2],或 struct { char a, b; },...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    • 2014-01-26
    • 2014-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    相关资源
    最近更新 更多