c++ - Visual C++ 开关控制路径僵局

标签 c++ visual-c++ visual-studio-2012

这会产生警告 C4715:并非所有控制路径都返回值。

int f_no_default(bool true_or_false)
{
    switch (true_or_false)
    {
    case (true) :
        return 1;
    case (false) :
        return 0;
    }
}

但这会产生警告 C4809:switch 语句具有多余的“默认”标签;给出了所有可能的“案例”标签。

int f_with_default(bool true_or_false)
{
    switch (true_or_false)
    {
    case (true) :
        return 1;
    case (false) :
        return 0;
    default:
        return 0;
    }
}

我能做什么? (除了关闭将警告视为错误)

Visual Studio 2013 V12.0

最佳答案

What can I do? (other than turn off treat warnings as errors)

下面的代码可能会修复它:

int f_no_default(bool true_or_false)
{
    switch (true_or_false)
    {
    case (true) :
        return 1;
    case (false) :
        return 0;
    }

    return 0; // <<<<<<<<<<<<<<<<<
}

对于这种情况,这是一个愚蠢的警告,但静态分析功能取决于实际的编译器实现,警告消息的有用性也是如此。


另一种选择(更符合您的函数名称)是抛出异常:

int f_no_default(bool true_or_false)
{
    switch (true_or_false)
    {
    case (true) :
        return 1;
    case (false) :
        return 0;
    }

    throw std::runtime_error("Unecpected value for 'true_or_false'");
}

关于c++ - Visual C++ 开关控制路径僵局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37172698/

相关文章:

c++ - QMetaType 是否与模板化类型一起使用

c++ - C2280 尝试引用已删除的函数

c++ - Visual C++ 9.0 (2008) 静态库 + Boost 库 = 大型 .lib 文件

c++ - 内联函数是如何编译成汇编的?

windows - 为什么我在 Visual Studio 2012 中没有收到 64 位警告,除非我打开 "deprecated"编译器开关?

c++ - close vs _close, read vs _read, write vs _write - 有什么区别?

c++ - 如何使用 unique_ptr 将 const 指针传递给 const 对象

c++ - 通过类成员函数访问静态常量变量的问题

c++ - 获取重载成员函数的返回类型

c# - 带有 C# .NET 4.5 的 XNA 4.0?