Learn/C/4. Making decisions
Lesson 4 of 15
Sign in

C, lesson 4

Making decisions

So far every line of your programs ran every time. Real programs choose: charge a child less, reject a bad password, print a warning when the tank is low. C makes these choices with if and switch.

if, else if, else

C checks the conditions from top to bottom and runs the first block whose condition is true, then skips the rest. The else block runs only if nothing above matched. Always use braces, even for one line: it prevents a whole family of bugs when you add a second line later.

Comparison operators

OperatorMeaning
==equal to
!=not equal to
<,

2 exercises to try what you just read.

Exercise 1

Leap year

Press Ctrl Enter or Check to test your code.

Exercise 2

Pocket calculator

Press Ctrl Enter or Check to test your code.

<=
less than, less than or equal
>, >=greater than, greater than or equal

Watch out for = versus ==. if (x = 5) assigns 5 to x and is then always true. GCC warns about it, which is one more reason to read warnings.

What counts as true

In C a condition is just a number: zero means false and anything else means true. Comparisons produce 1 or 0. C23 makes bool, true and false built-in keywords, so you can store a result with a clear name:

Logical operators

  • a && b is true when both are true.
  • a || b is true when at least one is true.
  • !a flips true and false.

Both && and || short-circuit: they stop as soon as the answer is known. In count > 0 && total / count > 10, the division never runs when count is zero, so the program cannot divide by zero. && binds more tightly than ||; add parentheses when you mix them so readers don't have to remember that.

The conditional operator

For a simple either/or value, condition ? a : b is shorter than a full if:

switch

When you compare one integer or character against several fixed values, switch reads well:

Each case label must be a constant. Execution jumps to the matching label and then keeps going until it hits break. Forgetting break makes it "fall through" into the next case, which is occasionally useful but usually a bug. If you fall through on purpose, mark it with the C23 attribute [[fallthrough]]; so readers and the compiler know it was intended. default catches every value that no case matched.

Further reading

  • cppreference: if statement
  • cppreference: switch statement
  • cppreference: Comparison operators
  • cppreference: Logical operators

A year is a leap year if it is divisible by 4, except years divisible by 100, which are leap years only if they are also divisible by 400. So 2024 and 2000 are leap years, but 1900 is not.

Read one year and print <year> is a leap year or <year> is not a leap year.

Read a calculation written as number operator number, for example 12 * 4. The numbers are integers and the operator is one of +, -, *, /. Print the result as an integer (division rounds toward zero, like C's /).

Special cases, each printed on its own line:

  • dividing by zero prints Error: division by zero
  • any other operator prints Error: unknown operator

Read the operator with " %c": the space before %c skips the blank after the first number. Use a switch on the operator.

int fuel = 12;

if (fuel == 0) {
    puts("Empty!");
} else if (fuel < 15) {
    puts("Low fuel, find a station.");
} else {
    puts("Fuel OK.");
}
bool is_weekend = day == 6 || day == 7;
if (is_weekend) {
    puts("Sleep in.");
}
int items = 1;
printf("%d item%s\n", items, items == 1 ? "" : "s");
char size = 'M';
switch (size) {
    case 'S': puts("Small"); break;
    case 'M': puts("Medium"); break;
    case 'L': puts("Large"); break;
    default:  puts("Unknown size");
}
Input:
2024
Output:
2024 is a leap year
Input:
12 * 4
Output:
48