C语言 “const struct”与“struct”有何不同?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4266914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:10:57  来源:igfitidea点击:

How does a 'const struct' differ from a 'struct'?

csyntax

提问by Manu

What does const structmean? Is it different from struct?

什么const struct意思?它不同于struct?

回答by GrahamS

The constpart really applies to the variable, not the structure itself.

const部分真正适用于变量,而不是结构本身。

e.g. @Andreas correctly says:

例如@Andreas 正确地说:

const struct {
    int x;
    int y;
} foo = {10, 20};
foo.x = 5; //Error

But the important thing is that variable foois constant, not the structdefinition itself. You could equally write that as:

但重要的是变量foo是常量,而不是struct定义本身。您同样可以将其写为:

struct apoint {
    int x;
    int y;
};

const struct apoint foo = {10, 20};
foo.x = 5; // Error

struct apoint bar = {10, 20};
bar.x = 5; // Okay

回答by Andreas Brinck

It means the structis constant i.e. you can't edit it's fields after it's been initialized.

这意味着它struct是恒定的,即在它被初始化后你不能编辑它的字段。

const struct {
    int x;
    int y;
} foo = {10, 20};
foo.x = 5; //Error

EDIT:GrahamS correctly points out that the constness is a property of the variable, in this case foo, and not the struct definition:

编辑:GrahamS 正确地指出常量是变量的属性,在这种情况下foo,而不是结构定义:

struct Foo {
    int x;
    int y;
};
const struct Foo foo = {10, 20};
foo.x = 5; //Error
struct Foo baz = {10, 20};
baz.x = 5; //Ok

回答by Nick

I believe that a const struct cannot be modified. In other words, all fields of a struct which is declared const are non-modifiable.

我相信不能修改 const 结构。换句话说,声明为 const 的结构体的所有字段都是不可修改的。

回答by Sudantha

Const means you cannot editthe field of the structure after the declaration and initialization and you canretrieve the data form the structure

const 表示在声明和初始化后不能编辑结构体的字段,并且可以从结构体中检索数据

回答by Jay

'const' as the word constant itself indicates means unmodifiable. This can be applied to variable of any data type. struct being a user defined data type, it applies to the the variables of any struct as well. Once initialized, the value of the const variables cannot be modified.

'const'作为常量本身表示意味着不可修改。这可以应用于任何数据类型的变量。struct 是用户定义的数据类型,它也适用于任何结构的变量。一旦初始化,const 变量的值就不能修改。

回答by kirubel

you can not modify a constant struct ,first struct is a simple data type so when a const key word comes on ,the compiler will held a memory space on a register rather than temporary storage(like ram),and variable identifiers that is stored on register can not be modified

你不能修改一个常量结构,第一个结构是一个简单的数据类型,所以当一个 const 关键字出现时,编译器将在寄存器上而不是临时存储(如 ram)上保存一个内存空间,以及存储在上面的变量标识符注册不能修改