Reply to post: Re: Ugh!

Keen to go _ExtInt? LLVM Clang compiler adds support for custom width integers

ST Silver badge

Re: Ugh!

> [ ... ] using bitfields in C structs and expecting to produce correct portable code is not going to work well.

Aside from the endianess problem, there's also the cost problem. Declaring

unsigned int i : 3;

does not create a bitfield of 3 bits. It creates an unsigned int, of which only 3 bits are usable. The remaining 29 bits are still there, they're just not accessible.

Depending on how good your compiler is, it might or might not warn if you then write something like this:

i = 19;

The accessible 3 bits in this example are accessed via shift + mask. This adds CPU cycles.

The cost of loading and storing the unsigned int is unavoidable. By using a bitfield, the compiler is forced to add shifts and and's to manipulate the bitfield, on top of the cost of loads and stores.

I've seen a lot of code that does something like this:

unsigned int isValid : 1;

instead of using a bool, under the incorrect assumption that this saves a lot of memory. It doesn't save any memory, and it's more expensive than just using a bool.

POST COMMENT House rules

Not a member of The Register? Create a new account here.

  • Enter your comment

  • Add an icon

Anonymous cowards cannot choose their icon

Biting the hand that feeds IT © 1998–2021