这会产生警告 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/