在switch case中使用指针值。 [英] Using a pointer value in switch case.
问题描述
#include <stdio.h>
int main() {
//code
int i=5;
int *p=&i;
printf ("%d", *p);
switch (*p)
{
case *p:
printf ("&&");
break;
}
return 0;
}
* p给出i的值。那么为什么这个程序会出错呢?
我尝试了什么:
Switch语句适用于整数表达式,而指针不是整数表达式。但是我传递了指针指向的值为5.那么这不应该运行吗?
*p gives value of i. Then why is this program running into error?
What I have tried:
Switch statement works on integral expressions and pointer is not an integral expression. But i am passing the value pointed by the pointer that is 5. So should this not run?
推荐答案
在开关盒中使用指针值。
Using a pointer value in switch case.
简答:对于你想要的,它是如果结构,不是switch。
Short answer: For what you want, it is if structure, not switch.
到目前为止,这个开关(* p)
还可以。但是这个案例* p:
就是问题所在。
为什么?
在c中查看Switch语句的定义,例如:这里:切换声明(C) [ ^ ]
定义说大小写常量-expression:
表示你需要为case部分使用常量Expression,而* p
是一个(解除引用的指针)变量,因此不允许在这里。
我希望这会有所帮助。
This oneswitch (*p)
is ok so far. But this onecase *p:
is the Problem.
Why?
Have a look to the Definition of the Switch Statement in c, e.g. here: switch Statement (C)[^]
The Definition sayscase constant-expression :
and means you Need to use a constant Expression for the "case part", while*p
is a (dereferenced pointer) variable and therefore not allowed here.
I hope this helps.
来自在C中切换语句 [ ^ ]
From switch statement in C[^]
以下规则适用转换语句
- switch语句中使用的表达式必须具有整数或枚举类型,或者是w中的类类型该类具有单个转换函数为整数或枚举类型。
- 您可以在一个开关中包含任意数量的case语句。每个案例后跟要比较的值和冒号。
- 案例的常量表达式必须与变量中的变量相同。切换,它必须是常量或字面值。
- 当接通的变量等于大小写时,该情况后的语句将执行,直到a达到break语句。
- 当达到break语句时,开关终止,控制流跳转到switch语句后的下一行。 />
- 并非每个案例都需要包含休息时间。如果没有出现中断,控制流将落到后续情况,直到达到中断。
- switch语句可以有一个可选的默认情况,必须出现在开关的末尾。当没有任何情况属实时,默认情况可用于执行任务。在默认情况下不需要中断。
The following rules apply to a switch statement
- The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.
- You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
- The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.
- When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
- When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
- Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
- A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
我认为你的指针不符合规则第一。
I think your pointer is not fitting in rule number one.
这篇关于在switch case中使用指针值。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!