gpt4 book ai didi

c++ - 为什么在将编译器从 G++ 切换到 MSVC 时此 switch 语句不返回任何内容?

转载 作者:行者123 更新时间:2023-11-27 23:49:28 26 4
gpt4 key购买 nike

<分区>

我正在帮助一位 friend 完成他的一项 C++ 作业,我们发现以下代码片段会在 MSVC 中引发异常,但在使用 G++ 进行编译时,完全相同的代码可以正常工作。返回异常是因为这个名为 getValue() 的函数没有返回任何东西。

string getValue(int value) {

ostringstream convert;

string rtnValue;

switch (value) {
case 11:
{
rtnValue = "J";
break;
}
case 12:
{
rtnValue = "Q";
break;
}
case 13:
{
rtnValue = "K";
break;
}
case 14:
{
rtnValue = "A";
break;
}
default:
{
//
// if the value is a a number, we assume it is 2..10
//
convert << value; // use a stream to convert the number
rtnValue = convert.str(); // into a string
if (value < 2 || value > 10)
{
rtnValue = "ERROR" + rtnValue + "ERROR";
}
}
return rtnValue;
}
}

此程序将整数转换为字符串。对于数字 11-14,它使用 switch 语句(我知道这不是最好的实现,但它是一个入门类(class))。

我们发现可以通过在末尾添加另一个 return 语句轻松解决这个问题。

string getValue(int value) {

ostringstream convert;

string rtnValue;

switch (value) {
case 11:
{
rtnValue = "J";
break;
}
case 12:
{
rtnValue = "Q";
break;
}
case 13:
{
rtnValue = "K";
break;
}
case 14:
{
rtnValue = "A";
break;
}
default:
{
//
// if the value is a a number, we assume it is 2..10
//
convert << value; // use a stream to convert the number
rtnValue = convert.str(); // into a string
if (value < 2 || value > 10)
{
rtnValue = "ERROR" + rtnValue + "ERROR";
}
}
return rtnValue;
}
return rtnValue;
}

这现在为 MSVC 修复了它(如果我检查过,我假设是 G++)。

为什么该修复有效? MSVC 和 G++ 在处理 switch 语句时是否以不同方式处理括号?

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