Hi everyone. 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 purpose of the :1. Can anybody clue me in? Thanks.
Hi everyone. 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 purpose of the :1. Can anybody clue me in? Thanks.
bitfield. x is 1 bit long.
Each field is accessed and manipulated as if it were an ordinary member of a structure. The keywords signed and unsigned mean what you would expect, except that it is interesting to note that a 1-bit signed field on a two's complement machine can only take the values 0 or -1. The declarations are permitted to include the const and volatile qualifiers.
The main use of bitfields is either to allow tight packing of data or to be able to specify the fields within some externally produced data files. C gives no guarantee of the ordering of fields within machine words, so if you do use them for the latter reason, you program will not only be non-portable, it will be compiler-dependent too. The Standard says that fields are packed into ‘storage units’, which are typically machine words. The packing order, and whether or not a bitfield may cross a storage unit boundary, are implementation defined. To force alignment to a storage unit boundary, a zero width field is used before the one that you want to have aligned.
Be careful using them. It can require a surprising amount of run-time code to manipulate these things and you can end up using more space than they save.
Bit fields do not have addresses—you can't have pointers to them or arrays of them.
http://publications.gbdirect.co.uk/c_book/chapter6/bitfields.html
That syntax is used to denote bit fields (i.e. fields of bits that are narrower than the data type itself), so the "x" in your example is really using 1 bit of an int.
A more useful example might be something like
char x:4;
char y:4;
This would pack two 4-bit fields into one byte. The advantage is, of course, to save space in architectures where every byte is critical.
It's a bit field that's 1 bit long. There's a good discussion on the wikipedia.
these are bit fields. in structs you can define how many bits are assigned to the variable (overriding the standard for the variable type)
in the example above x only uses 1 byte and can thus only take the value 0 or 1.
see the following example from the C book. 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's complement!
*/
signed field2 :1;
/* align next field on a storage unit */
unsigned :0;
unsigned field3 :6;
}full_of_fields;