什么是这个C ++警告 - 控制到达非void函数的结尾

时间:2017-11-24 18:32:03

标签: c++

我正在写这个函数定义。

#include<iostream>

int abs_fun(int x);

int main()
{
    int i =abs_fun(0);
    std::cout<<i;
    return 0;
}

int abs_fun(int x)
{
    if (x<0)
        return -x;
    else if(x>=0) //warning
        return x;
}

我正在使用g++ -Wall -Wconversion -Wextra p4.cpp -o p4编译代码并在abs_fun()结束时收到警告warning: control reaches end of non-void function [-Wreturn-type] }如果我只是写else而不是else if,那么警告消失了。有任何建议,为什么会出现警告?

4 个答案:

答案 0 :(得分:5)

因为编译器不够聪明(或者只是没有尝试)才能理解总是到达return之一。

答案 1 :(得分:2)

对于ifelse,如果ifelse分支都返回,则可以确保在所有情况下都返回某些内容。

在您的情况下,它需要进行分析以确定条件完全涵盖编译器不需要执行的所有可能的用例。在这种情况下,它很直接,但考虑更复杂的条件。如果需要分析这些简单的条件,那么我们将在哪里画线?&#34;就编译器应该分析的复杂程度而言。

答案 2 :(得分:0)

问题是所有控制路径都应该抛出异常或返回一些值。否则是未定义的行为,因此编译器想要警告您。在您的情况下,编译器无法证明所有执行路径都会导致返回/异常。

为什么?

因为检查费用很高。有时可能甚至不可能。因此,编译器只是没有这样的功能。

在哪些情况下?

嗯,这更多是关于离散数学。

答案 3 :(得分:-2)

假设一个函数签名:

 int fun( );
宣布

。 期望在某个执行阶段返回一个整数值
  有时,虽然函数完成执行而不返回任何值,但可能会发生,因为return语句可能不会执行。 参考示例:

int fun(void ) {
          cout<<"Executed";
       //Omit return --> return X;
}

它会生成带有警告的输出Warning: control reaches end of non-void function [-Wreturn-type]|

编译器假设总是可以访问return语句如果它不能保证它只是警告程序员。

当您对if值使用else if return条件时,无法保证会返回某些内容

check(2)

int check(int no) {
  if no>2
    return no;
  else if no<2
    return 2;
}

因此导致    C:\Users\Zahid\Desktop\sf\main.cpp|18|warning: control reaches end of non-void function [-Wreturn-type]| 如果缺少else

当我们对else值使用return条件时,肯定会将某些内容返回为:

 int check(int no) {
    if no>2
      return no;
    else 
  return 2;
}

因此导致执行没有任何错误。

回到你的代码

示例1

int abs_fun(int x)
{
 if (x<0)
    return -x;
 else if(x>=0) //warning control reaches end of non-void function [-Wreturn-type]|
    return x;
 }

无法保证else ifif将被执行,后跟return声明。
示例2

 int abs_fun(int x)
{
 if (x<0)
     return -x;
  else
    return x;  --RUNS WELL 
}

由于编译器会尽可能优化代码以加快执行示例2 可能编译为示例3 ,但无法确定。


示例3

int abs_fun(int x)
{
 if (x<0)
    return -x;
  //ELSE can always be commented out without any affect on output.  
    return x;  --
 }

结论:如果编译器无法保证返回值,则Warning: control reaches end of non-void function [-Wreturn-type]|会发出警告 否则它会正常执行而不会发出任何警告。