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

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

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

相关标签:
6条回答
  • 2020-12-23 13:57

    '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.

    0 讨论(0)
  • 2020-12-23 13:59

    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

    0 讨论(0)
  • 2020-12-23 14:02

    I believe that a const struct cannot be modified. In other words, all fields of a struct which is declared const are non-modifiable.

    0 讨论(0)
  • 2020-12-23 14:11

    Const means you cannot edit the field of the structure after the declaration and initialization and you can retrieve the data form the structure

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-23 14:20

    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
    
    0 讨论(0)
提交回复
热议问题