Boolean Operators
Sometimes we want to check multiple conditions at once, effectively saying things like "if something and something", or "if something or something". C has the following operators to do that:
&&
means and: the value ofa && b
is true if botha
andb
are true;||
means or: the value ofa || b
is true if eithera
, orb
, or both of them are true;!
means not: the value of!a
is true ifa
is false.
Note that they are &&
and ||
, but not &
and |
. To make things more confusing, &
and |
are valid operators too – they are called bitwise operators and do something completely different, which we'll discuss later. So just make sure to only use &&
and ||
for now.
Let's write some code. How about, maybe, a function which checks that the given number x
is between two other numbers a
and b
(inclusive)?
#include <stdio.h>
int is_between(int x, int a, int b) {
/* write the code! remember: 0 is false, everything else is true */
return 0;
}
int main() {
printf("is 1 between 3 and 7? %d\n", is_between(1, 3, 7));
printf("is 3 between 3 and 7? %d\n", is_between(3, 3, 7));
printf("is 5 between 3 and 7? %d\n", is_between(5, 3, 7));
printf("is 7 between 3 and 7? %d\n", is_between(7, 3, 7));
printf("is 9 between 3 and 7? %d\n", is_between(9, 3, 7));
return 0;
}