How does a 'const struct' differ from a 'struct'?
What does const struct
mean? Is it differ开发者_如何学JAVAent from struct
?
The const
part really applies to the variable, not the structure itself.
e.g. @Andreas correctly says:
const struct {
int x;
int y;
} foo = {10, 20};
foo.x = 5; //Error
But the important thing is that variable foo
is constant, not the struct
definition itself.
You could equally write that as:
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
It means the struct
is constant i.e. you can't edit it's fields after it's been initialized.
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:
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' 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 means you cannot edit the field of the structure after the declaration and initialization and you can retrieve the data form the structure
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
精彩评论