All lessons

Making Decisions

8 min · C

Run different code depending on whether something is true.

C · Making Decisions0/5 cleared

Enemy 1 of 5

if / else and comparison operators

An if statement lets your program choose between two paths. The condition inside ( ) is checked, and if it evaluates to true (in C, any non-zero value counts as true, and 0 counts as false), the { } block right after runs; otherwise it's skipped.

An else attached to that if provides the "otherwise" branch, running only when the if's condition was false. Together, if/else let a program make a decision instead of always doing the exact same thing every run.

Comparisons use > , < , >= , <= , == (equal to), and != (not equal to). Because C treats 0 as false and everything else as true, a very common beginner bug is writing if (x = 5) (a single = , which assigns 5 to x and is always true) when you meant if (x == 5) (a double ==, which actually compares). Watch for this — it's one of C's most infamous gotchas.

You
Memory-Leak Rat

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: Cold