0

I have an enum:

typedef enum {
    ALI = 0,
    
    JOHN,
    CATI,

} NAMES_e;

As I know, as long as the enum has less than 256 items, it uses 1 byte of RAM. The storage is so important for me, so as I'm developing the program, this might become even more than 1000 names (it might!) and I should be aware of it (To control the storage).

1. So, I tried this in the main function:

if (sizeof(NAMES_e) == 1)
    #error "NAMES_eis more than 256"

2. It didn't work. I also used the same with #if:

#if (sizeof(NAMES_e) == 1)
    #error "NAMES_eis more than 256"
#endif

I got this error:

error: token is not a valid binary operator in a preprocessor subexpression

I checked this (My compiler doesn't support static_assert and this. Nothing special.

3. I did this:

int size = sizeof(NAMES_e);
size = 1; //Just to test.
#if (size == 1) 
    #error "NAMES_e is more than 256"
#endif

And the compiler doesn't compile the last one either. No errors while compiling.

What should I do?

Mohammad Kholghi
  • 533
  • 2
  • 7
  • 21

1 Answers1

0

We can use a small trick! First, I should mention that the sizeof(char[0]) doesn't compile and throws an error. So, we take advantage of it!:

#define CHECK_SIZE(condition) ((void)sizeof(char[2 - (condition)]))
//...
CHECK_SIZE(sizeof(NAMES_e));

How does it work? If the NAMES_e is 2 bytes, it tries to check the sizeof(char[0]), which we talked about.

For more information, read this and this.

Mohammad Kholghi
  • 533
  • 2
  • 7
  • 21