Question about design C

I always thought I knew C very well until I saw something like this in another post:

struct foo { int x:1; }; 

I would really like to know the goal: 1. Can someone tell me? Thanks.

+4
source share
4 answers

bit. x has a length of 1 bit.

Each field is accessible and managed as if it were a regular member of the composition. Keywords signed and unsigned mean what you expect, except that it is interesting to note that a one-bit signed field on two add-on machines can only take values ​​0 or -1. Declarations allowed to include const and volatile qualifiers.

The main use of bit fields is to either provide tight data packaging or the ability to specify fields in some data files created externally. C does not guarantee the ordering of a field in machine words, so if you use them for the latter reason, the program will not only not be portable, it also depends on the compiler. The standard says that the fields are packed into β€œstorage units, which are usually machine words. The packing order, and whether a bit field can cross the boundary of the storage block, is an implementation defined. To force alignment with the border of the storage block, a zero-width field is used up to which you want align.

Use caution. This may require an amazing amount of code at runtime to manipulate these things, and you can end up using more space than they save.

There are no addresses in bit fields - you cannot have pointers to them or arrays of them.

http://publications.gbdirect.co.uk/c_book/chapter6/bitfields.html

+11
source

these are bit fields. in structures you can determine how many bits are assigned to a variable (overriding the standard for the type of variable)

in the above example, x uses only 1 byte and therefore can only take the value 0 or 1.

see the following example from book C. follow the link for more information.

 struct { /* field 4 bits wide */ unsigned field1 :4; /* * unnamed 3 bit field * unnamed fields allow for padding */ unsigned :3; /* * one-bit field * can only be 0 or -1 in two complement! */ signed field2 :1; /* align next field on a storage unit */ unsigned :0; unsigned field3 :6; }full_of_fields; 
+3
source

This bit field is 1 bit long. There is a good discussion on wikipedia .

+1
source

This syntax is used to denote bit fields (that is, bit fields that are narrower than the data type itself), so the "x" in your example really uses 1 int bit.

A more useful example might be something like

 char x:4; char y:4; 

This would drop two 4-bit fields into one byte. The advantage, of course, is saving space in architectures where every byte is critical.

0
source

Source: https://habr.com/ru/post/1286358/


All Articles