简体   繁体   中英

enum comparison in if statement never true in c

I am developing a program in ansi C, and I have some issues. I have an enum along the lines of

enum day
{
    Monday = 'M',
    Tuesday = 'T',
    Wednesday = 'W'
}

and a 2d array of days

typedef enum day availDays[numOfWeeks][daysOfWeek];
memset(theArray, Monday, sizeof(theArray));

later used in an if statement like this:

if ( theArray[0][0] == Monday )
    { foo statements; }

but that condition never evaluates to true even if every element of the array is Monday , any ideas why?

The reason this doesn't work is that sizeof(enum day) != 1 . So you can't use memset .

This happens because although you set every enum value to a char , the underlying type of the enum is not char . It is (most likely) int .

This is the reason why memset doesn't work. It sets each byte of the element to 'M'. As such each element will be a "concatenation" of the 4 bytes of value 'M'.

Assuming little endian, ASCII char encoding ( 'M' is 0x4D ) and sizeof(int) 4 , the array should look like this in memmory:

0x4D0000004D000000...

memset sets it to:

0x4D4D4D4D...

The only solution is to loop over the array and set each element individually

for (i...)
    for (j...)
        theArray[i][j] = Monday;

Moral of the story: use memset only for char buffers. char is the only type mandated by standard to have exactly size 1.


Although the question is about C , it is good to know for whoever needs this in C++ , that since C++11 you can specify the underlying type of an enum :

enum Day : char {
   ...
};

sizeof(Day) == 1; // true    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM