首页 > 解决方案 > C++ 函数的返回值

问题描述

我遇到了一个问题,在解决过程中我得到了以下功能:

bool interesting(int n){
    
    for(int i = 1; i <= n; i++){
        if(sum(n+1, 0) < sum(n, 0)
            return true;
        }
}

也就是说,给定一个数字 n 来验证下一个数字的总和(n+1,0)是否小于前一个数字。但是我想知道该函数是返回真还是假,因为我有多个 i 要循环。

标签: c++function

解决方案


int sum(int n, int m) { return -1; }
 
bool interesting(int n){

for(int i = 1; i <= n; i++){
    if(sum(n+1, 0) < sum(n, 0))
        return true;
    }
  // miss return here
}

int main() {}

这可能无法编译。即使它编译它也会产生一个未定义的行为。对于返回布尔值的函数,函数中的所有路径方式都应返回一个值。

警告:非 void 函数不会在所有控制路径中返回值

尝试编译代码

此外,一旦满足该条件,此函数将以 true 退出。我认为这是你需要的:

int sum(int n, int m) { return -1; }
     
bool interesting(int n){
    bool result = true;
    for(int i = 1; i <= n; i++){
        if(!(sum(n+1, 0) < sum(n, 0)))
            result = false;
        }
     return result;
 }

编辑:我错误地认为您的代码不会编译。碰巧在某些编译器上它确实编译但发出警告


推荐阅读