Why aren't bitfields allowed with normal variables?

前端 未结 5 1554
隐瞒了意图╮
隐瞒了意图╮ 2020-12-10 08:14

I wonder why bitfields work with unions/structs but not with a normal variable like int or short.
This works:

struct foo {
             


        
5条回答
  •  死守一世寂寞
    2020-12-10 08:51

    All objects must occupy one or more contiguous bytes or words, but a bitfield is not an object; it's simply a user-friendly way of masking out bits in a word. The struct containing the bitfield must occupy a whole number of bytes or words; the compiler just adds the necessary padding in case the bitfield sizes don't add up to a full word.

    There's no technical reason why you couldn't extend C syntax to define bitfields outside of a struct (AFAIK), but they'd be of questionable utility for the amount of work involved.

提交回复
热议问题