c - switch-case 中有效但毫无值(value)的语法?

标签 c switch-statement language-lawyer

通过一个小错别字,我无意中发现了这个构造:

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 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,强调我的):

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/

相关文章:

python - 如何在 Python 中搜索正则表达式匹配项?

c++ - 成员函数不能为 set iterator 和 const_iterator 的输入重载(但可以为其他 STL 迭代器重载)

css - 在 CSS 网格中有行号 2 而没有行号 1 是否有效?

c++ - 什么时候在空实例上调用成员函数会导致未定义的行为?

c - 16 位非负数的右旋?

c - 将哈希表传递给函数时数据丢失

Java - 方法程序 - 在方法中使用 switch case

c++ - 需要帮助使用 switch 语句创建函数和错误

c - 如何以不同模式在同一数据库上打开两个 SQLite 上下文?

c - 我陷入了c编程的困境,没有代码的概念