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)?
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.
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};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With