在C / C ++编程语言的结构初始化? [英] Struct initialization of the C/C++ programming language?

查看:118
本文介绍了在C / C ++编程语言的结构初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以做初始化结构与code:

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).

第二块的第二条语句是非常不同的。虽然看起来相似,它是分配前pression。这意味着,运营商平等的RHS是(独立是什么=的LHS)评估,然后传递给=操作一个前pression。如果没有适当的背景下, {...} 没有任何意义。

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 };

现在的运营商等于右手边是一个有效的前pression,由于编译器知道什么是适当的范围内{...}

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 ++编程语言的结构初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆