【问题标题】:Const Struct vs Struct With Const MembersConst Struct 与 Struct 与 Const 成员
【发布时间】:2020-07-09 17:05:23
【问题描述】:

这两者有区别吗?

typedef struct {
    unsigned int day;
    unsigned int month;
    unsigned int year;
}birthday_t;

typedef struct {
    const birthday_t birthday;
    const unsigned int id;
}person_t;

person_t person = {
    .birthday = {1,20,2000},
    .id = 123};

和

typedef struct {
    unsigned int day;
    unsigned int month;
    unsigned int year;
}birthday_t;

typedef struct {
    birthday_t birthday;
    unsigned int id;
}person_t;

const person_t person = {
    .birthday = {1,20,2000},
    .id = 123};

如果结构中的成员是 const 但结构不是常量(上),这与没有 const 成员的 const 结构不同(下)吗?

【问题讨论】:

  • 您能解释一下这是为什么吗?
  • 由于您专门标记了 C99,您可能只询问 C,而不询问 C++?
  • C 还是 C++?选择一种语言。
  • 我知道初始化成员时 C++ 的语法是不同的。但是,在示例中处理 const 的方式之间是否存在根本区别? C首选
  • .birthday = {1,20,2000}, 从什么时候开始第 20 个月存在?

标签: c struct constants c99


【解决方案1】:

主要区别在于意图之一。

typedef struct {
    const birthday_t birthday;
    const unsigned int id;
}person_t;

说没有person_t 可以更改其birthday 或id。

const person_t person = {
    .birthday = {1,20,2000},
    .id = 123};

(假设person_t 的第二个声明)表示此特定人员无法更改其birthday 或id,但其他人员对象可以。

【讨论】:

    【解决方案2】:

    在这里你让所有人都必须有常数(生日和身份证)

    typedef struct {
        const birthday_t birthday;
        const unsigned int id;
    }person_t;
    ```````````````````
    but here you made one person struct should be constant but other not
    ```````````````
    const person_t person = {
        .birthday = {1,20,2000},
        .id = 123};
    ``````````
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多