在if语句中的枚举比较从不在c中 [英] enum comparison in if statement never true in c
问题描述
我有一个
枚举
沿 枚举day
{
星期一='M',
星期二='T',
星期三='W'
}
和 2d数组
天
typedef枚举天availDays [numOfWeeks] [daysOfWeek];
memset(theArray,Monday,sizeof(theArray));
稍后在if语句中使用:
if(theArray [0] [0] == Monday)
{foo statements; }
但条件从不评估为 true
即使数组的每个元素都是星期一
,任何想法为什么?
p>这不行的原因是 sizeof(enum day)!= 1
。所以你不能使用 memset
。
这是因为尽管将每个枚举值设置为 char
,枚举的底层类型不是 char
。这是(很可能) int
。
这就是为什么 memset
不起作用它将元素的每个字节设置为M。因此,每个元素将是值M的4个字节的连接。
假设小端,ASCII字符编码( M'
是 0x4D
)和 sizeof(int)4
,数组应该看起来像这在memmory中:
0x4D0000004D000000 ...
memset
将其设置为:
0x4D4D4D4D ...
唯一的解决方案是循环遍历数组并单独设置每个元素(i ...)
(j ...)
theArray [i]
[j] =星期一
故事的道德:仅使用 memset
对于 char
缓冲区。 char
是标准规定的唯一尺寸为1的类型。
尽管问题是关于 C
,但是在 C ++
中需要知道谁是非常好的,因为 C ++ 11
您可以指定枚举的底层类型
:
枚举日:char {
...
};
sizeof(Day)== 1; // true
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
这篇关于在if语句中的枚举比较从不在c中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!