gpt4 book ai didi

c - 开关盒 : error: case label does not reduce to an integer constant

转载 作者:太空狗 更新时间:2023-10-29 16:22:09 27 4
gpt4 key购买 nike

int value;

const int signalmin = some_function();

switch(value)
{
case signalmin:
break;
}

我读取了 some_function 的值并使用该 int 值来打开 switch case。 C99 编译器返回:

error: case label does not reduce to an integer constant

但我不能使用 #define,因为在执行 switch 之前正在读取 int 值。

最佳答案

switch 标签必须是常量表达式,它们必须在编译时求值。如果您想在运行时值上进行分支,则必须使用 if

const 限定的变量不是常量表达式,它只是一个不允许修改的值。

整数常量表达式的形式详见6.6(6)【C99和C2011标准的n1570草案】:

6 An integer constant expression shall have integer type and shall only have operands that are integer constants, enumeration constants, character constants, sizeof expressions whose results are integer constants, _Alignof expressions, and floating constants that are the immediate operands of casts. Cast operators in an integer constant expression shall only convert arithmetic types to integer types, except as part of an operand to the sizeof or _Alignof operator.

仅允许结果为整数常量的 sizeof 表达式的限制排除了操作数为可变长度数组的 sizeof 表达式。

关于c - 开关盒 : error: case label does not reduce to an integer constant,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14069737/

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