开发者

Is there a way to keep some members of a struct unmodifiable?

开发者 https://www.devze.com 2023-03-11 18:31 出处:网络
I have a struct : struct ABC { int size; int arr[15]; }; I know I cannot make \'int size\' as开发者_StackOverflow \'const int size\' so how can I keep the size member from being modified accidently

I have a struct :

struct ABC
{
   int size;
   int arr[15];
};

I know I cannot make 'int size' as开发者_StackOverflow 'const int size' so how can I keep the size member from being modified accidently/intentionally.Is there a way around in C?

Thanks.


It can be const:

struct ABC
{
   const int size;
   int arr[15];
};

int main() {
    struct ABC a = {3, {1,2,3} };   // ok
    a.size = 42;    // error
}
0

精彩评论

暂无评论...
验证码 换一张
取 消