有效,但在转换情况下毫无价值的语法吗? [英] 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\n"); // This line is Unreachable
case 'a': printf("A\n"); break;
case 'b': printf("B\n"); break;
case 'c': printf("C\n"); break;
case 'd': printf("D\n"); 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
)具有以下示例:
The standard (N1579 6.8.4.2/7
) has the following sample:
在人工程序片段中的示例
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\n", 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
语句的条件到案例标签的转移在这方面被认为是跳跃.
90) The transfer from the condition of a switch
statement to a case label is considered a jump in this respect.
因此,用int i;
替换int i = 4;
使其成为有效的C ++.
So replacing int i = 4;
with int i;
makes it a valid C++.
这篇关于有效,但在转换情况下毫无价值的语法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!