gpt4 book ai didi

c++ - 是否有 g++ 标志可以在 switch 语句中检测并警告此无法访问的代码?

转载 作者:行者123 更新时间:2023-12-05 05:33:22 26 4
gpt4 key购买 nike

这不是完全可能的最小复制,但希望在一口大小的同时很好地说明问题。

#include <iostream>

int main(int, char **)
{
int i;
std::cin >> i;

switch(i)
{
case 0:

break;
std::cout << "too small" << std::endl;

case 1:
break;

default:
std::cout << "too large" << std::endl;
break;
}

return 0;
}

当然,这里的问题是用户在中断之后而不是之前向 switch 语句添加了代码。 (当然,在一个真实的例子中,在 break 语句之前会有预先存在的代码)

clang 能够通过 -Wunreachable-code 标志检测到这一点,而 MSVC 能够通过 /Wall 检测到它,但我还没有找到方法让 g++ 对此发出警告。

g++ 确实有一个标记-Wswitch-unreachable,但它只捕获出现在第一个开关标签之前的代码,所以它在这里没有帮助。

最佳答案

这在 Eljay 和 Jerry Jeremiah 的评论中基本上得到了解决,但是为了解决这个问题,gcc 似乎在 2014 年默默地删除了无法访问的代码检测,因为它在不同的优化级别给出了不同的结果。

对于删除每个编译器应该具有的最基本和最重要的功能之一来说,这似乎是一个非常愚蠢的理由,但我知道什么?

来自 gcc 邮件列表:

The -Wunreachable-code has been removed, because it was unstable: itrelied on the optimizer, and so different versions of gcc would warnabout different code. The compiler still accepts and ignores thecommand line option so that existing Makefiles are not broken. Insome future release the option will be removed entirely.

来源: https://gcc.gnu.org/legacy-ml/gcc-help/2011-05/msg00360.html

关于c++ - 是否有 g++ 标志可以在 switch 语句中检测并警告此无法访问的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73873989/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com