Re: somebody dropped a (warning) bomb

Linus Torvalds
2007-02-08T23:37:56Z

On Thu, 8 Feb 2007, David Rientjes wrote:
>
> And a compiler that makes a_variable.flag unsigned would be brain-dead
> because "int" is always signed.

No, making bitfields unsigned is actually usually a good idea. It allows
you to often generate better code, and it actually tends to be what
programmers _expect_. A lot of people seem to be surprised to hear that a
one-bit bitfield actually often encodes -1/0, and not 0/1.

So unsigned bitfields are not only traditional K&R, they are also usually
_faster_ (which is probably why they are traditional K&R - along with
allowing "char" to be unsigned by default). Don't knock them. It's much
better to just remember that bitfields simply don't _have_ any standard
sign unless you specify it explicitly, than saying "it should be signed
because 'int' is signed".

I will actually argue that having signed bit-fields is almost always a
bug, and that as a result you should _never_ use "int" at all. Especially
as you might as well just write it as

signed a:1;

if you really want a signed bitfield.

So I would reall yrecommend that you never use "int a:<bits>" AT ALL,
because there really is never any good reason to do so. Do it as

unsigned a:3;
signed b:2;

but never

int c:4;

because the latter really isn't sensible.

"sparse" will actually complain about single-bit signed bitfields, and it
found a number of cases where people used that "int x:1" kind of syntax.

Just don't do it.

Linus