Operators and Expressions

Article · 2:00

Arithmetic through bitwise, sizeof, and the precedence rules that decide what your expression means.

The arithmetic, relational and logical operators are what you expect, with two things worth stating. Integer division truncates toward zero, and % gives the remainder - which for negative operands follows the division, so -7 / 2 is -3 and -7 % 2 is -1. And && and || short-circuit: the right-hand side is not evaluated if the left already decides the answer, which is what makes if (p != NULL && p->value > 0) safe.

Increment and decrement come in two forms. ++i increments and yields the new value; i++ yields the old value and then increments. Using both in one expression - a[i] = i++ - is undefined behaviour, because the standard does not say which happens first.

The bitwise operators work on the individual bits: & is and, | is or, ^ is exclusive or, ~ inverts, and << and >> shift. These are not obscure in C - they are how you pack flags into one integer, how you talk to hardware registers, and how a hash function mixes bits. Shifting a signed negative number right is implementation-defined, so shift unsigned types.

sizeof is an operator, not a function, evaluated at compile time. It gives the size in bytes of a type or an expression, and it is how you write code that does not assume an int is four bytes.

Precedence is where real bugs live. & and | bind looser than ==, so if (flags & MASK == 0) parses as flags & (MASK == 0) and is almost never what was meant. The rule in practice: use parentheses whenever bitwise and comparison appear together.

#include <stdio.h>

#define FLAG_READ   (1u << 0)   /* 0001 */
#define FLAG_WRITE  (1u << 1)   /* 0010 */
#define FLAG_EXEC   (1u << 2)   /* 0100 */

int main(void)
{
    printf("%d %d\n", -7 / 2, -7 % 2);    /* -3 and -1: truncates to zero */

    /* Short-circuit: the right side is not evaluated at all, which is
       what makes the NULL check on the left meaningful. */
    int *p = NULL;
    if (p != NULL && *p > 0) { /* never dereferenced */ }

    int i = 5;
    printf("%d %d %d\n", i++, i, ++i);  /* unspecified order - avoid */

    unsigned flags = 0;
    flags |= FLAG_READ | FLAG_WRITE;         /* set   */
    flags &= ~FLAG_WRITE;                    /* clear */
    flags ^= FLAG_EXEC;                      /* toggle */

    /* THE precedence trap: & binds LOOSER than ==, so without the
       parentheses this reads as flags & (FLAG_READ == 0), which is
       flags & 0, which is 0. */
    if ((flags & FLAG_READ) == 0) {
        printf("not readable\n");
    }

    printf("flags = %u\n", flags);
    printf("int %zu, double %zu, array %zu\n",
           sizeof(int), sizeof(double), sizeof(int[10]));
    return 0;
}