在if语句中的枚举比较从不在c中

编程入门 行业动态 更新时间:2024-10-26 21:18:36
本文介绍了在if语句中的枚举比较从不在c中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在ansi 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中

本文发布于:2023-11-27 09:38:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637542.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!