C - Confused by 'control can reach the end of a non-void function' when using certain if / else syntax

When defining a function in C, I get the error message "control can reach the end of a non-void function" in the compiler when writing if / else logic in a certain way (script 1 below), but I don't get an error when writing logic in a different way (script 2 below). For me, both ways of writing this function seem similar, so I don’t understand why version 1 will not compile.

Scenario 1

bool search(int value, int values[], int n) { int i; if (n<1) { return false; } for(i=0;i<n;i++) { if (value==values[i]) { return true; } else { return false; } } } 

Scenario 2

 bool search(int value, int values[], int n) { int i; if (n<1) { return false; } for(i=0;i<n;i++) { if (value==values[i]) { return true; } } return false; } 

Would script 2 always return false after a for loop? Or is the function essentially β€œStop” after returning the value for the first time, so it returns β€œtrue” after the value matches [i]?

+6
source share
1 answer

The problem is that the C compiler is not smart enough to realize that there is no script when the first function reaches the end without returning a value:

  • When a loop is executed at least once, there is a conditional return from both branches of the if statement, and
  • When the loop is never executed, it will return from the conditional statement at the top of the function.

The C standard does not require such checks, so the compiler generates a warning.

+6
source

All Articles