Comparisons and True or False
Check the room capacity
So far, expressions have calculated counts and measurements. A comparison calculates an answer to a yes-or-no question. A room with 12 attendees and 15 spaces still has room; a full room does not.
| Operator | Question |
|---|---|
< | Is the left value less than the right? |
<= | Is it less than or equal to the right? |
> | Is it greater than the right? |
>= | Is it greater than or equal to the right? |
== | Are the values equal? |
!= | Are the values different? |
Comparisons produce an int: 1 for true or 0 for false. This is a Boolean result, meaning a true/false answer. In a C condition, zero counts as false and any nonzero value counts as true; you do not need a separate Boolean type for these examples.
#include <stdio.h>
int main(void) {
int attendees = 12;
int capacity = 15;
printf("Space: %d\n", attendees < capacity);
printf("Full: %d\n", attendees == capacity);
printf("Valid: %d\n", attendees > 0 && attendees <= capacity);
return 0;
}
Run the example. 12 < 15 gives 1; 12 == 15 gives 0. The final expression combines two comparisons with &&, meaning both must be true. Twelve is greater than zero and no greater than the capacity, so Valid is 1.
|| means at least one condition is true. ! reverses a truth value: !0 is 1, and applying ! to any nonzero value gives 0. Like comparisons, these logical operators produce 0 or 1. Do not confuse == with =: the first compares; the second assigns a value.
Stop when the answer is known
&& checks its left operand first. If that is false, it skips the right operand. For example, divisor != 0 && total / divisor > 2 skips the division when divisor is zero. This is called short-circuit evaluation. || skips its right operand when its left operand is already true.
If the attendee count were 15, Space would be 0, Full would be 1, and Valid would still be 1. These boundary values help check whether you chose < or <= deliberately.