Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

I came across some structure declarations with colons and numbers next to certain fields, like this: struct record { char *name; int refcount : 4; unsigned dirty : 1; }; What gives?

0
Posted

I came across some structure declarations with colons and numbers next to certain fields, like this: struct record { char *name; int refcount : 4; unsigned dirty : 1; }; What gives?

0

Those are bit-fields; the number gives the exact size of the field, in bits. (See any complete book on C for the details.) Bit-fields can be used to save space in structures having several binary flags or other small fields, and they can also be used in an attempt to conform to externally-imposed storage layouts. (Their success at the latter task is mitigated by the fact that bit-fields are assigned left-to-right on some machines and right-to-left on others). Note that the colon notation for specifying the size of a field in bits is only valid in structures (and in unions); you cannot use this mechanism to specify the size of arbitrary variables. (See questions 1.2 and 1.3.) References: K&R1 Sec. 6.7 pp. 136-8 K&R2 Sec. 6.9 pp. 149-50 ISO Sec. 6.5.2.1 H&S Sec. 5.6.5 pp. 136-8 comp.lang.c FAQ list · Question 2.26 Q: Why do people use explicit masks and bit-twiddling code so much, instead of declaring bit-fields? A: Bit-fields are thought to be nonportable, although they are no less port

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123