return Can Return an Expression
There are several ways how you could write the is_between function on the previous page. First of all, you could've avoided using any boolean operators at all:
int is_between(int x, int a, int b) {
if (x < a) {
return 0; /* remember: return exits the function */
}
if (x > b) {
return 0;
}
return 1;
}
You could've combined that into one expression with || or with && – the following implementations do the same thing:
int is_between(int x, int a, int b) {
if (x < a || x > b) {
return 0;
}
return 1;
}
int is_between(int x, int a, int b) {
if (x >= a && x <= b) {
return 1;
}
return 0;
}
But one thing I haven't explicitly mentioned above is that you can avoid using if by writing a single return statement:
int is_between(int x, int a, int b) {
return (x >= a && x <= b);
}
The way it works is: as you remember, each comparison operator results in 0 or 1, and the && will evaluate to 1 (a true value) if it sees a true value on both sides.
Depending on a situation, it might be easier to squeeze the function logic into a single return statement, or have multiple conditions with individual return statements.