Boolean expressions are expressions that are true or false. They can be combined and manipulated with the operators &&, read "AND" and ||, read "OR" and ! read "NOT". Recall that non-zero values are considered true, and 0 is false.
Look at the expression
age>6 && age<90The compound expression is true only if both the first expression and the second expression are true. If either expression is false the compound expression is false. The expressions are evaluated from left to right. If the first expression is false, C will NOT evaluate the second expression. Let's put the expression above in a small program:
int main() { printf("Enter your age.\n"); int age; scanf("%d", &age); if (age>6 && age<90) //old enough but not too old printf("You may cross the street on your own."); else printf("You may NOT cross the street by yourself."); }Now let's consider the other operator
c == 'a' || c == 'b'This compound expression is false only if both expressions are false. Otherwise it is true. Again we have left to right evaluation. If the first expression is true, the second expression will not be evaluated. Here is a program example.
int main() { printf("Please enter a lower case letter.\n"); char c; scanf("%c", &c); if (c=='a' || c=='b') printf("Your letter is either a or b.\n"); else printf("Your letter is nither an a nor b.\n"); }Let's look at an example where the non-evaluation of the expression on the right might be useful.
int main() { int a[] = {7, 2, 19, 44, 5, 137, 54, 8, 66, 23}; printf("Ten numbers are stored in positions 0 through 9. "); printf("Enter a position,\n"); printf("if the number at that position is bigger that 100, "); printf("you win a prize.\n"); int i; scanf("%d", &i); if (i>=0 && i<10 && a[i]>100) printf("Congatulations, you WIN this message!\n"); else printf("You lose. Sorry, try again.\n"); }Array
a
needs to be protected from the user putting in an index
that is too small (less than 0) or too large (larger than 9) If either of the
first two conditions is false, the value in i will NOT be plugged into array
a.
Finally we come to the operator ! It changes true to false and false to true. Below we see a use of !.
if ( !(age<3) && sex=='F') printf("You are a big girl now.\n");