Struct initialization of the C/C++ programming language?(C/C++ 编程语言的结构初始化?)
问题描述
我可以用代码进行结构初始化:
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++ 编程语言的结构初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C/C++ 编程语言的结构初始化?


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09