switch-case 中有效但毫无价值的语法? [英] Valid, but worthless syntax in switch-case?
问题描述
通过一个小错字,我偶然发现了这个结构:
Through a little typo, I accidentally found this construct:
int main(void) {
char foo = 'c';
switch(foo)
{
printf("Cant Touch This
"); // This line is Unreachable
case 'a': printf("A
"); break;
case 'b': printf("B
"); break;
case 'c': printf("C
"); break;
case 'd': printf("D
"); break;
}
return 0;
}
看来 switch
语句顶部的 printf
是有效的,但也完全无法访问.
It seems that the printf
at the top of the switch
statement is valid, but also completely unreachable.
我得到了一个干净的编译,甚至没有关于无法访问代码的警告,但这似乎毫无意义.
I got a clean compile, without even a warning about unreachable code, but this seems pointless.
编译器是否应该将此标记为无法访问的代码?
这有什么用吗?
Should a compiler flag this as unreachable code?
Does this serve any purpose at all?
推荐答案
也许不是最有用的,但也不是完全一文不值.您可以使用它来声明 switch
范围内可用的局部变量.
Perhaps not the most useful, but not completely worthless. You may use it to declare a local variable available within switch
scope.
switch (foo)
{
int i;
case 0:
i = 0;
//....
case 1:
i = 1;
//....
}
标准(N1579 6.8.4.2/7
)有以下示例:
示例 在仿真程序片段中
EXAMPLE In the artificial program fragment
switch (expr)
{
int i = 4;
f(i);
case 0:
i = 17;
/* falls through into default code */
default:
printf("%d
", i);
}
标识符为 i
的对象存在自动存储期限(在块内)但从不已初始化,因此如果控制表达式具有非零值,则对 printf
函数的调用将访问一个不确定的值.同样,无法调用函数f
.
the object whose identifier is i
exists with automatic storage duration (within the block) but is never
initialized, and thus if the controlling expression has a nonzero value, the call to the printf
function will
access an indeterminate value. Similarly, the call to the function f
cannot be reached.
P.S.顺便说一句,该示例不是有效的 C++ 代码.在那种情况下(N4140 6.7/3
,强调我的):
P.S. BTW, the sample is not valid C++ code. In that case (N4140 6.7/3
, emphasis mine):
一个程序从一个具有自动存储持续时间的变量不在范围内的点跳转90到一个它在范围内的点是不正确的除非变量具有标量类型,类类型具有微不足道的默认值构造函数和普通析构函数,其中一种类型的 cv 限定版本,或其中一种类型的数组前面的类型并且在没有初始化器的情况下声明 (8.5).
A program that jumps90 from a point where a variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has scalar type, class type with a trivial default constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the preceding types and is declared without an initializer (8.5).
90) 从 switch
语句的条件到 case 标签的转移在这方面被认为是一个跳转.
90) The transfer from the condition of a switch
statement to a case label is considered a jump in this respect.
因此,将 int i = 4;
替换为 int i;
使其成为有效的 C++.
So replacing int i = 4;
with int i;
makes it a valid C++.
这篇关于switch-case 中有效但毫无价值的语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!