Signed vs unsigned bit-fields
What you'll learn: How the signed and unsigned keywords dramatically change the range of values a bit-field can hold.
When you define a bit-field, you are telling the computer exactly how many bits of memory to use for a variable. However, there is a common "gotcha" regarding the most significant bit—the one on the far left.
The sign bit surprise
Imagine you have a tiny bucket that can hold exactly 3 bits. If you declare this as an unsigned int, those three bits are all used for the value itself. You can store any number from 0 to 7.
However, if you declare it as a signed int, C uses the leftmost bit as a "sign bit" to track whether the number is positive or negative. This leaves you with only 2 bits for the actual number. In a 3-bit signed field, the value 111 doesn't mean 7; in most systems (using two's complement), it actually represents -1!
Seeing it in action
If you aren't careful, a signed bit-field might "overflow" into a negative number much sooner than you expect. This is why bit-fields used for flags or small counters are almost always declared as unsigned.
#include <stdio.h>
struct Data {
unsigned int u_field : 1; // Range: 0 to 1
signed int s_field : 1; // Range: -1 to 0 (or just 0)
};
int main() {
struct Data d;
d.u_field = 1;
d.s_field = 1;
// u_field will print 1
printf("Unsigned: %u\n", d.u_field);
// s_field might print -1!
// This is because 1 was the only bit available,
// and the computer treats it as the sign bit.
printf("Signed: %d\n", d.s_field);
return 0;
}
Why it matters
Choosing between signed and unsigned is about more than just "positive or negative." It’s about how many "usable" bits you have. For a 1-bit field, making it signed is usually a mistake because that single bit becomes the sign bit, leaving you with no bits left for the magnitude. You end up with a variable that can only represent 0 and -1 (or 0 and -0, depending on the compiler).
If you are using bit-fields to save space or interface with hardware, stick to unsigned unless you specifically need to represent negative numbers. It keeps the math predictable and ensures that "what you see is what you get."
Key takeaway
Always use unsigned for bit-fields unless you specifically need to store negative values, as the sign bit consumes one of your limited bits.