How does a 'const struct' differ from a '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