Const Struct 与 Const 成员的结构

Const Struct vs Struct With Const Members

这两个有区别吗?

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 结构(下)是否不同?

主要区别在于意图之一。

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

说没有 person_t 可以改变它的 birthdayid

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

(假设 person_t 的第二个声明)说这个特定的人不能改变它的 birthdayid,但其他人的对象可能。

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

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};
``````````