gpt4 book ai didi

c - 为什么模数对 int 和 enum 的处理方式不同?

转载 作者:太空宇宙 更新时间:2023-11-04 02:00:57 26 4
gpt4 key购买 nike

如果运行以下代码,您会发现模数结果对于整数可能为负,但对于枚举始终为正。

这对我来说没问题(我用它来循环选项菜单列表),但我想确保它是一个 ANSI 约束,而不是编译器实现。

#include <stdio.h>

enum targets {
TARGET1,
TARGET2,
TARGET3,
TARGET4,
NUMTARGETS,
};

int main() {
int i;
enum targets selected_enum = TARGET3;
int selected_int = TARGET3;

for (i = 0; i < 10; i++) {
selected_enum = (selected_enum - 1) % NUMTARGETS;
printf("Selected_enum = %d\n", selected_enum); /* I only see positive values */
}

for (i = 0; i < 10; i++) {
selected_int = (selected_int - 1) % NUMTARGETS;
printf("Selected_int = %d\n", selected_int); /* I see negative values */
}

return 0;
}

最佳答案

首先你得写

selected_enum = ( enum targets )( ( selected_enum - 1 ) % NUMTARGETS );

代替

selected_enum = ( selected_enum - 1 ) % NUMTARGETS;

至于你得到的结果是实现定义的。

根据C标准(6.7.2.2枚举说明符)

4 Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined,128) but shall be capable of representing the values of all the members of the enumeration. The enumerated type is incomplete until immediately after the } that terminates the list of enumerator declarations, and complete thereafter.

And(6.3 转换,6.3.1.1 bool 值、字符和整数)

— The rank of any enumerated type shall equal the rank of the compatible integer type

例如 MS VC++ 2010 输出

Selected_enum = 1
Selected_enum = 0
Selected_enum = -1
Selected_enum = -2
Selected_enum = -3
Selected_enum = 0
Selected_enum = -1
Selected_enum = -2
Selected_enum = -3
Selected_enum = 0
Selected_int = 1
Selected_int = 0
Selected_int = -1
Selected_int = -2
Selected_int = -3
Selected_int = 0
Selected_int = -1
Selected_int = -2
Selected_int = -3
Selected_int = 0

看来您使用的编译器将枚举兼容类型定义为无符号类型。

尝试运行下面的代码

#include <stdio.h>

int main( void )
{
enum targets { TARGET1, TARGET2, TARGET3, TARGET4, NUMTARGETS, };

int i;
enum targets selected_enum = TARGET3;
int selected_int = TARGET3;

for ( i = 0; i < 10; i++ )
{
if ( ( selected_enum = ( enum targets )( selected_enum - 1 ) ) >= 0 ) printf( "unsigned %u\n", +selected_enum );
else printf( "signed %d\n", selected_enum );
}


return 0;
}

在 www.ideone.com 上运行这个程序后,我得到了

unsigned 1
unsigned 0
unsigned 4294967295
unsigned 4294967294
unsigned 4294967293
unsigned 4294967292
unsigned 4294967291
unsigned 4294967290
unsigned 4294967289
unsigned 4294967288

而 MS VC++ 2010(和在线 MS VC++ 2014 编译器)输出

unsigned 1
unsigned 0
signed -1
signed -2
signed -3
signed -4
signed -5
signed -6
signed -7
signed -8

关于c - 为什么模数对 int 和 enum 的处理方式不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27294478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com