C comparison operators (==, !=, <, >) and logical operators (&&, ||, !).
| Operator | Meaning | Result for a=3, b=5 |
|---|---|---|
a == b | Equal | 0 (false) |
a != b | Not equal | 1 (true) |
a > b | Greater | 0 (false) |
a >= b | Greater or equal | 0 (false) |
a < b | Less | 1 (true) |
a <= b | Less or equal | 1 (true) |
| Operator | Meaning | Reads as | Example |
|---|---|---|---|
A && B | A AND B (both true) | AND | age >= 18 && age < 65 |
A || B | A OR B (either true) | OR | day == 0 || day == 6 |
!A | NOT A | NOT | !finished |
| A | B | A && B |
|---|---|---|
| true | true | true |
| true | false | false |
| false | true | false |
| false | false | false |
| A | B | A || B |
|---|---|---|
| true | true | true |
| true | false | true |
| false | true | true |
| false | false | false |
== vs = — Critical!if (a = 10) when you meant ==. This assigns 10 to a and then uses 10 as the condition, which is always true.// BUG if (a = 10) { // = is assignment! a becomes 10 and condition is always true printf("Always runs\n"); } // correct if (a == 10) { // == is comparison. True only when a equals 10 printf("a is 10\n"); }
== is "check equal", = is "put into".condition ? value_if_true : value_if_false// using if-else int max; if (a > b) { max = a; } else { max = b; } // one line with ternary int max = (a > b) ? a : b;
| Use | Example | Meaning |
|---|---|---|
| Max of two values | (a > b) ? a : b | a if a is greater, otherwise b |
| Absolute value | (x >= 0) ? x : -x | x if non-negative, otherwise -x |
| Even / odd label | (n%2==0) ? "even" : "odd" | Can be passed directly to printf |
| Avoid divide-by-zero | (b != 0) ? a/b : 0 | Divide if b isn't 0, otherwise 0 |
(a>b) ? ((a>c)?a:c) : ((b>c)?b:c) are hard to read — use if-else instead.Check your understanding of this lesson!
= is assignment; == is the equality (comparison) operator. === does not exist in C (that is a JavaScript operator).
1 && 0 = 0 (false), and negating it gives !0 = 1 (true).
5 > 3 is true (1); 2 > 4 is false (0). && is true only if both are, so 1 && 0 = 0 (false).
Learning the concepts here + doing exercises in a book is very effective
* These are affiliate links. Your purchases help support this site.