Lesson contents

C — Comparisons and short-circuit operators

C evaluates the operands of && from left to right and stops at the first false operand. This makes ordered bounds checks useful before an array access.

A simple example

Test two conditions

  1. Start with n is 2
  2. Do this Greater than 0 and less than 3?
  3. Result yes
Both comparisons succeed, so the program prints yes.
lesson.c
#include <stdio.h>

int main(void) {
    int n = 2;
    if (n > 0 && n < 3) {
        puts("yes");
    }
}
Output
yes
Advertisements

Operator examples

Operation Expression Result
Integer division 7 / 2 3
Remainder 7 % 2 1
Comparison 5 >= 5 1
Equality 3 == 4 0
Logical conjunction 1 && 0 0
Bit mask 6 & 3 2

Guard an indexed lookup

Combine comparisons with a short-circuiting logical operator. Check that a zero-based index is within bounds before reading the element at that index. Keep both bounds checks to the left of stock[i]. An array subscript outside its valid range has undefined behavior in C.

Shelf quantities: 2 and 5. Order needs: At least 5. Second shelf: 5 available.
Look up a shelf safely

A stock scanner receives a shelf position before it knows whether that shelf exists. Check the bounds first. Only an existing shelf with at least five units can supply the order.

Run the example

Use a C17 compiler. Run these commands from the directory containing the example. Use a Unix-style shell.

cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson
lesson.c
#include <stdio.h>

int main(void) {
    int stock[] = {2, 5};
    int indices[] = {-1, 1, 2};
    for (int n = 0; n < 3; ++n) {
        int i = indices[n];
        if (i >= 0 && i < 2 && stock[i] >= 5) puts("take");
        else puts("skip");
    }
    return 0;
}
Output
skip
take
skip

Only index 1 is in bounds in the three trial lookups. Its value is exactly the threshold of 5, so it passes the inclusive comparison.

Try it yourself

Try index 0, then change its value from 2 to 5. How does its classification change?

Check your answer

Index 0 is valid in both cases. It changes from skip to take when its value reaches 5.

WG14 C language draft (PDF)

Related tags

  • C
  • operators
  • short-circuit evaluation
  • bounds checks