问题描述
我可以用代码进行结构初始化:
I could do struct initialization with code:
struct struct_type_id struct_name_id = { value1, value2, value3 };
但不能:
struct struct_type_id struct_name_id;
struct_name_id = { value1, value2, value3 };
为什么我用前者可以,而用gcc、g++、vc2008、vc6就不能用后者?换句话说,为什么c/c++编程语言不支持这种语法?
why I could do it with the former,but could not with the latter with gcc,g++,vc2008,vc6?In other words,why the c/c++ programming language do not support this syntax?
谢谢.
推荐答案
第一条语句创建了一个初始化为给定值的变量,即,这些值被构建在内存中并直接存储在该变量地址中的程序可执行文件中(对于全局变量)或准备好进行内存复制(用于堆栈变量).
The first statement creates a variable initialized to the given values, i.e., these values are built in memory and stored directly in the program executable in that variable address (for globals) or ready for memory copy (for stack variables).
第二块的第二条语句很不一样.虽然看起来很像,但它是一个赋值表达式.这意味着等号运算符的 RHS 是一个表达式,它被评估(独立于 = 的 LHS 中的内容),然后传递给 = 运算符.没有适当的上下文,{...}
没有任何意义.
The second statement of the second block is very different. Although it looks similar, it is an assign expression. It means that the RHS of the equals operator is an expression that is evaluated (independently of what is in the LHS of =), and then passed to the = operator. Without proper context, {...}
doesn't have any meaning.
在 C99 中,您可以这样做:
In C99, you can do this:
struct_name_id = (struct struct_type_id){ value1, value2, value3 };
现在等号运算符的 RHS 是一个有效的表达式,因为编译器有适当的上下文可以知道 {...}
中的内容.
Now the RHS of the equals operator is a valid expression, since there is proper context for the compiler to know what is in {...}
.
在 C++11 中,语法是:
In C++11, the syntax is:
struct_name_id = struct_type_id{ value1, value2, value3 };
这篇关于C/C++ 编程语言的结构初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!