Const Struct vs Struct With Const Members

Viewed 1580

Is there a difference between these two?

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

And

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

If a member inside a structure is const but the structure isn't constant (top), is this different than a const structure with not const members(bottom)?

2 Answers

The primary difference is one of intent.

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

says no person_t can ever change its birthday or id.

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

(assuming the second delcaration of person_t) says this specifc person cannot change its birthday or id, but other person objects might.

here you made all person must have constant (birthday and id)

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

Related