2

I have a struct :

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

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

Thanks.

rsjethani
  • 2,179
  • 6
  • 24
  • 30

1 Answers1

7

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
}
  • 2
    This will not prevent intentional modification though pointer manipulation. Just as a note for the OP. – rerun Jun 06 '11 at 07:56
  • @Neil-isn't this(struct var initialization) a feature of C99? – rsjethani Jun 06 '11 at 09:34
  • @ryan Sorry, I'm not sure what you are asking about - you've always been able to initialise structs. and C99 *is* what C is today - it's not some weird offshoot. –  Jun 06 '11 at 09:42
  • @ryanlancer: You're probably thinking of designated initializers, which were added in C99. That isn't this. – jamesdlin Jun 06 '11 at 10:22