我在功能方面遇到了一个小问题。我相信这可能是因为我没有正确使用它们。我的代码如下:
int duration(string fraction)
{
// X part of the fraction
int numerator = fraction[0];
// Y part of the fraction
int denominator = fraction[2];
// Checking for eighth note, quarter note and half note
if (numerator == 1)
{
switch (denominator)
{
case 8:
return 1;
case 4:
return 2;
case 2:
return 4;
}
}
// Checking for dotted quarter note
else
return 3;
}
Run Code Online (Sandbox Code Playgroud)
我的代码有什么问题导致我收到此特定错误:
错误:控制可能到达非 void 函数的末尾 [-Werror,-Wreturn-type]
numerator当is1和denominatoris时发生的事情10将不会返回任何内容 - 并且使用该函数考虑到它将返回某些内容将导致未定义的行为。
这就是警告的全部内容。
有很多方法可以解决这个问题 - 在语句default中放置一个 caseswitch或在函数中放置一个 return 语句(也许这会指定发生的一些错误事件)。您将返回什么值是您根据函数返回的值进行的选择。这是完全不同的讨论。
...
if (numerator == 1)
{
switch (denominator)
{
case 8:
return 1;
case 4:
return 2;
case 2:
return 4;
default:
return -1; // whatever value satisfies your application's need.
}
}
...
Run Code Online (Sandbox Code Playgroud)