简体   繁体   English

C中if语句中的枚举比较

[英]enum comparison in if statement never true in c

I am developing a program in ansi C, and I have some issues. 我正在用ansi C开发程序,但遇到了一些问题。 I have an enum along the lines of 我有一个enum

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

and a 2d array of days 2d array days 2d array

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

later used in an if statement like this: 以后在类似if的语句中使用:

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? 但是,即使数组的每个元素都是Monday ,该条件也永远不会为true ,有什么想法吗?

The reason this doesn't work is that sizeof(enum day) != 1 . 这不起作用的原因是sizeof(enum day) != 1 So you can't use memset . 所以你不能使用memset

This happens because although you set every enum value to a char , the underlying type of the enum is not char . 发生这种情况的原因是,尽管您将每个枚举值都设置为char ,但是枚举的基础类型不是char It is (most likely) int . (很可能是) int

This is the reason why memset doesn't work. 这就是memset不起作用的原因。 It sets each byte of the element to 'M'. 它将元素的每个字节设置为“ M”。 As such each element will be a "concatenation" of the 4 bytes of value 'M'. 这样,每个元素将是值“ M”的4个字节的“串联”。

Assuming little endian, ASCII char encoding ( 'M' is 0x4D ) and sizeof(int) 4 , the array should look like this in memmory: 假设字节序少,ASCII字符编码( 'M'0x4D )和sizeof(int) 4 ,则该数组在内存中应如下所示:

0x4D0000004D000000...

memset sets it to: memset将其设置为:

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. 故事的寓意:仅将memset用于char缓冲区。 char is the only type mandated by standard to have exactly size 1. char是标准规定的唯一大小精确为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 : 尽管问题是关于C ,但最好还是知道谁需要C++ ,因为从C++11您可以指定enum的基础类型:

enum Day : char {
   ...
};

sizeof(Day) == 1; // true    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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