typestar

Conditionals in C

Branching with if/else and the ternary operator.

const char *classify(int n) {
    if (n < 0)
        return "negative";
    else if (n == 0)
        return "zero";
    else
        return n % 2 == 0 ? "positive even" : "positive odd";
}

How it works

  1. An if/else if/else ladder returns at the first match.
  2. The ?: ternary chooses between two expressions.
  3. Each branch returns a string literal.

Keywords and builtins used here

The run, in numbers

Lines
8
Characters to type
152
Tokens
51
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 36 seconds.

Type this snippet

Step 2 of 7 in Operators & flow, step 9 of 35 in Language basics.

← Previous Next →

Conditionals in other languages