切换C编程
我这个代码仅用于学习目的。 但在这样做时我发现了一个问题。 这里x是常数整数,仍然编译器给我错误。 我正在使用gcc编译器。 请解释这个错误的原因是什么以及如何避免它。
#include int main() { int const x = 10; int y = 20; switch(y) { case x: //error: case label does not reduce to an integer constant printf("value of x: %d\n",x); break; } }
您可以使用预处理器作为解决方法:
#define X 10 // ... case X:
C语言中switch语句的语法如下:
selection-statement: switch ( expression ) statement labeled-statement: case constant-expression : statement default : statement
因此,您只能将常量表达式用作“案例值”。 常量表达式与常量变量不同 。 换句话说 – 抱歉,但你做不到。
您可能知道x
是常量但编译器无法保证它: 仍然可以在C中修改x
。一种方法是通过获取其地址(通过指针)并取消引用它。
在C中你只能打开文字整数类型; 更正式,一个不断的表达 。
在这种情况下,您必须使用if
语句,因为C的switch()
不接受表达式。 它需要一个常数。
case
语句需要常量。 你可以完成类似于你用宏做的事情。
#define TEN 10 #include int main() { int const x = TEN; int y = 20; switch(y) { case TEN: //error: case label does not reduce to an integer constant printf("value of x: %d\n",x); break; } }