</>CodexBash
C
CBeginner9 min

Decisions with if, else and switch

Choosing what runs with if, else if and else, why braces matter, the ternary operator, and switch for one value compared against many.

An if / else if chainstep 1/5
>=90
A
>=75
B
>=60
C
else
F
marks = 72
marks is 72. Each condition is checked in order, top to bottom.

if and else#

int temperature = 31;

if (temperature > 30) {
    printf("It's hot\n");
} else if (temperature > 20) {
    printf("It's warm\n");
} else {
    printf("It's cool\n");
}

The condition goes in brackets, the body in braces. C checks each condition in turn and runs the first branch that is true, then skips the rest.

Any number can be a condition: 0 is false and everything else is true. So if (count) means "if count is not zero".

Always use braces#

Braces are optional when a branch is one statement, but leaving them out invites a well-known bug:

if (x > 0)
    printf("positive\n");
    count++;              // looks like part of the if, but always runs

Indentation means nothing to the compiler. With braces, what you see is what runs.

Combining conditions#

if (age >= 18 && has_ticket) { ... }
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { ... }
if (!found) { ... }

The ternary operator#

A compact choice between two values:

int larger = (a > b) ? a : b;
printf("%s\n", (n % 2 == 0) ? "even" : "odd");

Read it as "if a is greater than b, a, otherwise b". Keep it for short choices; nested ternaries are hard to read.

switch#

When one value is compared against many fixed alternatives, switch is tidier than a chain of else if:

switch (day) {
    case 1:
        printf("Monday\n");
        break;
    case 6:
    case 7:
        printf("Weekend\n");
        break;
    default:
        printf("Weekday\n");
}

Two things to know:

  • break ends each case. Without it, execution falls through into the next case. That is occasionally useful, as with 6 and 7 above sharing one body, but usually a forgotten break is a bug.
  • switch works on whole numbers and characters only, not strings or doubles. For strings, use if with strcmp.

Comparing doubles#

Floating-point results are approximate, so never test them with ==:

double x = 0.1 + 0.2;
if (x == 0.3) { ... }                 // false
if (fabs(x - 0.3) < 1e-9) { ... }     // true; fabs is in <math.h>

Handling the odd cases first#

Checking special cases at the top and leaving early keeps the main logic flat:

int digits(int n) {
    if (n == 0) {
        return 1;
    }
    int count = 0;
    while (n != 0) {
        n /= 10;
        count++;
    }
    return count;
}

Key points#

  • if, else if, else: only the first true branch runs.
  • Zero is false; anything else is true.
  • Always write braces, even around one line.
  • cond ? a : b chooses between two values.
  • switch needs break in each case, and only works on integers and characters.

Next: repeating work with loops.

Practise it

The same idea, in the order it is worth meeting it.

  1. Not startedReads the same backwardsEasy
Create a free account to track your progress