如果 x 具有枚举类型, x * x (和类似的)是否会导致违反约束?

Does x * x (and similar) lead to constraint violation if x has enumerated type?

C11, 6.2.5 类型, 18:

Integer and floating types are collectively called arithmetic types.

C11, 6.2.5 类型, 16:

An enumeration comprises a set of named integer constant values. Each distinct enumeration constitutes a different enumerated type.

C11,6.5.5 乘法运算符,约束,2(添加了重点):

Each of the operands shall have arithmetic type.

示例代码:

enum E { a };
int f(enum E x)
{
        return x * x;
}

调用:

$ gcc t0.c -std=c11 -pedantic -Wall -Wextra -c
<nothing>

$ clang t0.c -std=c11 -pedantic -Wall -Wextra -c
<nothing>

$ icc t0.c -std=c11 -pedantic -Wall -Wextra -c
<nothing>

$ cl t235.c /std:c11 /Za /c
<nothing>

问题:x * x(和类似的)会导致违反约束吗?

据我了解,操作数x枚举类型,不是算术类型

枚举类型是整数类型,属于算术类型。没有违反约束条件。

来自 n1548:6.2.5.17

The type char, the signed and unsigned integer types, and the enumerated types are collectively called integer types.

如您所述,“整数类型”是算术类型。

我不明白你指的是什么约束。

根据 C 标准(6.2.5 类型)

17 The type char, the signed and unsigned integer types, and the enumerated types are collectively called integer types. The integer and real floating types are collectively called real types.

运算符 * 是为整数类型定义的,因为它们是算术类型的一部分。

18 Integer and floating types are collectively called arithmetic types.

只是您需要记住,将运算符应用于枚举类型的对象与其枚举数之间存在差异。 C 中的枚举器始终具有 int 类型,而兼容的整数枚举类型是实现定义的。

考虑以下演示程序。

#include <stdio.h>

int main(void) 
{
    enum E { a = 1 };
    
    enum E e = a;
    
    printf( "e * -1 < 0 is %d\n", e * -1 < 0);
    printf( "a * -1 < 0 is %d\n", a * -1 < 0);

    return 0;
}

它的输出可以是

e * -1 < 0 is 0
a * -1 < 0 is 1

与 C 在 C++ 中相反,枚举不是整数类型,但是无作用域的枚举可以提升为整数类型。