Operators & Expressions
Arithmetic, comparison, logical, bitwise, and the one typo that sank more systems than any other
In a nutshell
C’s operators look almost identical to Java’s. Almost. Integer division still truncates. Short-circuit evaluation still applies to && and ||. But two differences land silent bugs. & and && are different operators (bitwise vs logical), and = is a legal expression in C, so if (x = 5) compiles cleanly, assigns 5 to x, and always enters the body. That last mistake is the subject of Lab 1’s first reflection question and a decades-long class of CVEs.
Why it matters
Integer division (gpa * (5 / 4) evaluating to gpa * 1) is the silent-wrong-answer bug in Lab 1’s “GPA on 5.0 scale” line. The = vs == trap is CWE-481, which has produced everything from credit-card approval bugs to authentication bypasses. Short-circuit evaluation (p != NULL && *p == 'A') is how working C code survives the absence of null-safety. These are small typographic things with large real-world consequences.
Key takeaways
- Integer division truncates toward zero.
5 / 2is2;-7 / 2is-3. At least one operand must bedoublefor floating-point division. &&is logical AND;&is bitwise AND. Same for||vs|. Mixing them up gives the wrong answer on some inputs.- Short-circuit evaluation is a guard, not just an optimization.
if (p != NULL && *p == 'A')works only because&&skips the right operand when the left is false. =is a legal expression.if (x = 5)compiles, assigns, and always runs the body. Use-Wall(catches most) or Yoda conditionsif (5 == x)(catches all).- Precedence has two traps.
<<binds looser than+/-, and&/|bind looser than==. When in doubt, add parentheses.
Lessons in this topic
| Lesson | What it covers |
|---|---|
| Operators & Expressions | Arithmetic, comparison, logical, bitwise, sizeof, precedence, and the = vs == trap with all three reasons it is destructive |
Practice and deep dives
Practice this topic: C Operators drill, or browse the practice gallery.
For the full exploit mechanics of the = vs == class of bugs and four other CWEs that land in Lab 1’s reflection, see the memory-safety deep dive.
What comes next
Control Flow & Functions — if/else, switch fall-through (bug and feature), loops in C90 style, and how functions pass arguments by value.