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

后端 未结 6 1503
刺人心
刺人心 2020-12-23 13:57

What does const struct mean? Is it different from struct?

6条回答
  •  [愿得一人]
    2020-12-23 14:15

    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
    

提交回复
热议问题