Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 919
Peter Avatar asked Jul 17 '26 03:07

Peter


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

like image 138
Jasper Kent Avatar answered Jul 18 '26 19:07

Jasper Kent


Here you made all variables of type person_t have their birthday and id fields be constant:

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

But here you made it so that only the person variable is constant, but any other variable with type person_t can be declared as non-constant, and therefore have all its properties modified.

const person_t person = {
    .birthday = {1,20,2000},
    .id = 123};
like image 24
sara hamdy Avatar answered Jul 18 '26 21:07

sara hamdy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!