【问题标题】:How does a 'const struct' differ from a 'struct'?“const struct”与“struct”有何不同?
【发布时间】:2011-05-15 02:14:29
【问题描述】:

const struct 是什么意思?和struct 有区别吗?

【问题讨论】:

    标签: c syntax


    【解决方案1】:

    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
    

    【讨论】:

      【解决方案2】:

      这意味着struct 是常量,即在初始化后您无法编辑它的字段。

      const struct {
          int x;
          int y;
      } foo = {10, 20};
      foo.x = 5; //Error
      

      编辑: GrahamS 正确指出常量是变量的属性,在本例中为 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
      

      【讨论】:

      • 干杯。我的观察可以得到 +1 吗? :D
      【解决方案3】:

      我相信 const 结构不能被修改。换句话说,声明为 const 的结构的所有字段都是不可修改的。

      【讨论】:

        【解决方案4】:

        Const 表示您在声明和初始化后无法编辑结构的字段,并且您可以从结构中检索数据

        【讨论】:

          【解决方案5】:

          'const' 作为常量本身表示的意思是不可修改的。这可以应用于任何数据类型的变量。 struct 是用户定义的数据类型,它也适用于任何结构的变量。一旦初始化,const变量的值就不能修改了。

          【讨论】:

            【解决方案6】:

            你不能修改一个常量结构,第一个结构是一个简单的数据类型,所以当一个 const 关键字出现时,编译器将在寄存器上保存一个内存空间而不是临时存储(如 ram),以及变量标识符存储在寄存器上,不能修改

            【讨论】:

            • 这是不正确的。该结构未存储在寄存器中。
            猜你喜欢
            • 2020-07-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-07-29
            • 2018-07-03
            • 1970-01-01
            • 2020-11-17
            相关资源
            最近更新 更多