Search code examples
cstructconstantsc99

Const Struct vs Struct With Const Members


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)?


Solution

  • 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 declaration of person_t) says this specifc person cannot change its birthday or id, but other person objects might.