Const结构与具有Const成员的结构

问题描述 投票:0回答:1

这两者之间有区别吗?

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成员的const结构(底部)不同吗?

c struct const c99
1个回答
4
投票

主要区别是意图之一。

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,但其他人可以更改。

© www.soinside.com 2019 - 2024. All rights reserved.