Course Content
C Basics
C Basics
Comparison Operators
Understanding Comparison Operators
Comparison operators let you evaluate and compare values. One of the trickier aspects of these operators is remembering the correct order or arrangement of the symbols, like determining whether <
or =
should come first.
Below is a table of commonly used comparison operators:
Operation | Symbol | Usage Example |
Equality | == | a == b |
Inequality | != | a != b |
Greater than | > | a > b |
Less than | < | a < b |
Greater than or equal to | >= | a >= b |
Less than or equal to | <= | a <= b |
When these operators are used in a program, the outcome will be either true
or false
. In the context of programming, true
is typically represented as 1
, and false
is represented as 0
.
Main
#include <stdio.h> int main() { printf("Expression 8 == 7 + 1 is %d\n", 8 == 7 + 1); printf("Expression 10 != 3 is %d\n", 10 != 3); printf("Expression 7 > 7 is %d\n", 7 > 7); printf("Expression 20 >= 19 is %d\n", 20 >= 20 ); printf("Expression 21 <= 21 is %d\n", 20 <= 21 ); return 0; }
You'll frequently see comparison operators in loops and conditional statements.
Operator Precedence
Grasping the order of operations, or operator precedence, is crucial.
Note
Consider the equation: 2 + 2 * 2. What's your answer? If you thought it's 8, don't worry — you're not alone. Even the course creator has had moments of math confusion.
When it comes to precedence, the increment (++
) and decrement (--
) operators are evaluated first. This is followed by the multiplication (*
) and division (/
) operators. Lastly, the addition (+
) and subtraction (-
) operators are evaluated.
Take this code for instance:
To clarify the order of operations, you can use parentheses. So, the expression:
Can be more explicitly written as:
Thanks for your feedback!