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.
__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.
#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;
}2
3
31
-1
40Use 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.