通过一个小错别字,我无意中发现了这个构造:
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
似乎是有效的,但也完全无法访问。
我得到了一个干净的编译,甚至没有关于无法访问代码的警告,但这似乎毫无意义。
编译器是否应该将此标记为无法访问的代码?
这有什么用吗?
最佳答案
也许不是最有用的,但并非完全毫无值(value)。您可以使用它来声明一个在 switch
范围内可用的局部变量。
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\n", i); }
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 theprintf
function will access an indeterminate value. Similarly, the call to the functionf
cannot be reached.
P.S. 顺便说一句,示例不是有效的 C++ 代码。在那种情况下(N4140 6.7/3
,强调我的):
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) 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++。
关于c - switch-case 中有效但毫无值(value)的语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41727415/