Skip to content
systemcoding.dev
Fundamentals

Count trailing zeros with __builtin_ctz

Count trailing zeros in C with __builtin_ctz on GCC and Clang, and guard the zero case, because the builtin is undefined for an input of 0.

1 min read
Summarize in AI

__builtin_ctz returns the number of zero bits below the lowest set bit, which is also the index of that bit. It is the quickest way to turn a bitmask of ready tasks or free slots into a number. GCC documents that the result is undefined when the argument is 0, so the zero check is yours to write.

ctz.cc
#include <stdio.h>

static int lowest_index(unsigned int mask) {
    if (mask == 0)
        return -1;
    return __builtin_ctz(mask);
}

int main(void) {
    printf("%d\n", lowest_index(12u));
    printf("%d\n", lowest_index(40u));
    printf("%d\n", lowest_index(0x80000000u));
    printf("%d\n", lowest_index(0u));
    printf("%d\n", __builtin_ctzll(1ULL << 40));
    return 0;
}
Text
2
3
31
-1
40

Use the ll variant for a 64-bit value, because __builtin_ctz takes an unsigned int and silently drops the upper half. On x86 the compiler emits bsf or tzcnt; on a CPU without a fast instruction it falls back to a library call. C23 adds stdc_trailing_zeros in <stdbit.h>, which returns the type's width for an input of 0 and so removes the guard but needs a C23 library, so the builtin stays the portable choice for now. The GCC builtins page lists the whole family.

Taggedcgcc
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.