-1

I came with a problem, and during the solution I got the following function:

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

This is, given a number n to verify if the sum(n+1,0) of the next number is smaller than the previous. However I wonder if the function is going to return true or false, since I have multiple i's to be looped.

  • 7
    This function (after fixing the missing parentheses) is going to return `true` or exhibit [undefined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior). There is no case where the function remains well-defined and returns false. – Silvio Mayolo Jul 22 '21 at 16:44
  • You miss a return at end. – Jarod42 Jul 22 '21 at 16:44

1 Answers1

1
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() {}

This might not compile. Even if it compiles it will yield an undefined behavior. For a function returning a bool all paths ways in the function should return a value.

Warning: non-void function does not return a value in all control paths

Try to compile the code.

Also, once that condition is met this function will exit with true. I think this is what you need:

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

Edit: I was wrong to assume that your code won’t compile. It happens that on some compilers it does compile but emits a warning

Oussama Ben Ghorbel
  • 2,132
  • 4
  • 17
  • 34