为什么结构不能直接赋值? [英] Why structs cannot be assigned directly?
问题描述
假设我有一个完全定义的结构体,标签为 MyStruct
,并假设 x, y, ..., z
是其字段的允许值.为什么是
Suppose I have a fully defined struct with tag MyStruct
, and suppose that x, y, ..., z
are allowed values for its fields. Why is
struct MyStruct q = {x,y,..,z};
允许,但是
struct MyStruct q;
q = {x,y,...,z};
不允许?我觉得这很烦人.第二种情况,我之前已经声明了q
,我需要给每个字段一个一个赋值:
is not allowed? I find this very annoying. In the second case, where I have previously declared q
, I need to assign a value to each field, one by one:
q.X = x; q.Y = y; ... q.Z = z;
其中 X, Y, ..., Z
是 MyStruct
的字段.这背后有什么原因吗?
where X, Y, ..., Z
are the fields of MyStruct
. Is there a reason behind this?
推荐答案
您正在寻找的是复合字面量.这是在 C99 中添加到语言中的.
What you are looking for is a compound literal. This was added to the language in C99.
您的第一个案例:
struct MyStruct q = {x,y,..,z};
是特定于初始化的语法.你的第二种情况,在语言学派中不是初始化,而是赋值.赋值的右侧必须是正确类型的结构.在 C99 之前,该语言中没有用于编写结构体字面量的语法,而这正是您要尝试做的.{x,y,..,z} 看起来像一个包含表达式的块.如果有人受到启发,试图将其视为字面值,尽管语言没有这样做,但人们无法确定其类型.(在您的上下文中,您可以做出很好的猜测.)
is a syntax specific to initialization. Your second case, in the pedantics of the language is not initialization, but assignment. The right hand side of the assignment has to be a struct of the correct type. Prior to C99 there was no syntax in the language to write a struct literal, which is what you are trying to do. {x,y,..,z} looked like a block with an expression inside. If one were inspired to try to think of it as a literal value, though the language didn't, one couldn't be sure of its type. (In your context, you could make a good guess.)
为了允许这样做并解决类型问题,C99 添加了语法以便您可以编写:
To allow this and resolve the type issue, C99 added syntax so you could write:
q = (struct MyStruct){x,y,...,z};
这篇关于为什么结构不能直接赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!