【问题标题】:control reaches end of non-void function [-Wreturn-type]控制到达非空函数的结尾 [-Wreturn-type]
【发布时间】:2019-10-26 18:44:13
【问题描述】:

我写了一个这样的代码片段:

int gnrt(vector <int> vect, int n)
{
    std::vector <int> :: iterator it;
    it = find(vect.begin(), vect.end(), n);
    if(it!=vect.end()) gnrt(vect, n+1);
    else return n;
}

我试图找到一个与向量内的任何元素都不相似的数字 n。但它一直显示警告:

In function 'int gnrt(std::vector<int>, int)':
warning: control reaches end of non-void function [-Wreturn-type]

请任何人解释这里发生了什么。

【问题讨论】:

    标签: c++ algorithm function stdvector


    【解决方案1】:

    问题出在这里:

    if(it!=vect.end()) gnrt(vect, n+1);
        else return n;
    

    您的 if 案例没有返回值。

    你可能想这样做:

    if (it!=vect.end()) 
         return gnrt(vect, n+1);
    else 
         return n;
    

    我不知道您使用的是什么编译器,但通常会显示生成错误或警告的行以帮助您找到问题。

    【讨论】:

      【解决方案2】:

      你的函数应该返回一个int

      int gnrt(vector <int> vect, int n)
      

      但是您的代码不会返回该代码

      if(it!=vect.end()) gnrt(vect, n+1);
          else return n;
      

      稍微重新安排应该表明如果if condition 评估为true vitz,it!=vect.end() 你什么也不返回,编译器对此不满意

      if(it!=vect.end()) 
          gnrt(vect, n+1); // this one 
       else 
           return n;
      

      您的函数实际上有几个退出点。

      1. 正常的退出点,即被 { } 包围的函数的结束
      2. return 声明

      因为这个函数期望从所有这些出口点返回一些 int 值,所以任何未发现的出口点都是潜在的警告

      【讨论】:

      • 谢谢!我应该在这里考虑基本情况。
      猜你喜欢
      • 1970-01-01
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-29
      相关资源
      最近更新 更多