const struct
是什么意思?它和 struct
有什么不同?
“const
”关键字实际上是应用于变量而非结构本身。
例如,@Andreas 的说法是正确的:
const struct {
int x;
int y;
} foo = {10, 20};
foo.x = 5; //Error
但是重要的是变量 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
这意味着该struct
是常量,即在初始化后不能编辑其字段。
const struct {
int x;
int y;
} foo = {10, 20};
foo.x = 5; //Error
编辑:GrahamS 正确指出 const 属性是变量 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
Const 意味着在声明和初始化后,您无法编辑结构的字段,但可以从结构中检索数据
你不能修改一个常量结构体,因为第一个结构体是一个简单的数据类型,所以当 const 关键字出现时,编译器会在寄存器上保留一个内存空间,而不是临时存储(如 RAM),存储在寄存器上的变量标识符是不能被修改的。