Gra*_*amS 74
该const部分确实适用于变量,而不是结构本身.
例如@Andreas正确地说:
const struct {
int x;
int y;
} foo = {10, 20};
foo.x = 5; //Error
Run Code Online (Sandbox Code Playgroud)
但重要的是变量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
Run Code Online (Sandbox Code Playgroud)
And*_*nck 21
这意味着它struct是常量,即在初始化之后你不能编辑它的字段.
const struct {
int x;
int y;
} foo = {10, 20};
foo.x = 5; //Error
Run Code Online (Sandbox Code Playgroud)
编辑: GrahamS正确地指出constness是变量的属性,在这种情况下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
Run Code Online (Sandbox Code Playgroud)