This seems contradicting that search function will return true when
the value is found using for loop and then return false.
Not really. A return statement is capable of returning from a function (i.e., ending the function's execution and returning control to the caller).
A function either returns a value or it does not. In case it returns a value, the type of the value returned is specified as part of the function's signature. This type is often referred to as the function's return type. An example on a function's return type is the type bool
in
bool search(int values[], int value, int n)
{
// some code
}
A function that does not return a value has return type void
as it
void foo(int x)
{
// some code
}
In case a function returns a value, it has to be guaranteed that the closing brace that is delimiting the body of the function is never reached before a value of the specified return type is returned (using a return statement). For example
int abs(int x)
{
if (x < 0)
return -x;
return x;
}
If the statement return x;
was omitted, it would be possible that the closing brace of the function abs
is reached before returning a value of type int
, that is, when x >= 0
in which case the body of the if statement is never executed.
Having the statement return x;
after the body of the if statement above guarantees that x
is returned whenever x < 0
is false
.
If, however, the body of the if
statement was executed (i.e., x < 0
) was true
, the statement return -x;
is executed and the function terminates immediately with the value -x
returned to the caller.
By default, a function that does not return any value (i.e., has the return type void
) terminates as the closing brace that is delimiting its body is reached. However, you can still forcibly terminate the execution of this function at any point by having a return;
statement. For example,
void foo (int x)
{
if (x > 0)
return;
printf("I got here!\n"); // executed only when x <= 0
}
For more information, you may watch the short on functions!