【问题标题】:Control may reach end of non-void function [-Werror,-Wreturn-type]控制可能到达非空函数的结尾 [-Werror,-Wreturn-type]
【发布时间】:2018-01-21 07:06:36
【问题描述】:

我在功能方面有一点问题。我相信这很可能是因为我没有正确使用它们。我的代码如下:

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;
}

我收到此特定错误的代码有什么问题:

错误:控制可能到达非空函数的结尾 [-Werror,-Wreturn-type]

【问题讨论】:

  • 自己检查一下。如果numerator 是1,但denominator 是,比如16。函数会返回什么?
  • 编译器不知道你只有八分音符、四分音符和二分音符。在你的 switch 中添加一个default case,表明不可能发生的事情。
  • else 在这里是多余的。
  • switch() 语句缺少default: 的情况,因此会留下一个不包含return value 语句的执行路径。

标签: c


【解决方案1】:

numerator1 并且denominator10 时会发生什么,那么它不会返回任何东西 - 并且考虑到它会返回一些东西而使用该函数将导致未定义的行为。

这就是警告的全部内容。

有很多方法可以解决这个问题 - 在 switch 语句中添加 default 案例或在函数中添加 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. 
       }
    }
    ...

【讨论】:

  • @adityapatel.: 这完全与这个问题无关……你在代码中定义了main() 吗?确保没有印刷错误,如果没有;请提出新问题...我很乐意提供帮助。
【解决方案2】:

如果denominator 的值不是 2、4、8,它将在下面的评论中结束。

(假设numerator 为1)

在那里放一个return语句!

int duration(string fraction)
{
// X part of the fraction
int numerator = fraction[0];
// Y part of the fraction
int denominator = fraction[2];
// Checking for eigth note, quatar note and half note
if (numerator == 1)
{
    switch (denominator)
    {
        case 8:
        return 1;
        case 4:
        return 2;
        case 2:
        return 4;
   }
   // Got here and about to leave function without a return value
}
// Checking for dotted quater note
else
    return 3;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    相关资源
    最近更新 更多