Code:
struct info{
int x:1;
int y:1;
};
Single bit bit-fields should be declared as unsigned int to ensure either 0 or 1 as valid values. Most of the time such a bit-field is to be used as a binary flag, and having 1 as an invalid value would definitely cause problems.
>Now doesn't that creat two variables that can only hold a value of 1 or 0 right.
Not necessarily, but if you make them unsigned, yes that is correct.
>Could someone help me understand and find a practical use for this plz??
Bit-fields can be easier that regular bit twiddling:
Code:
struct {
unsigned good :1;
unsigned fail :1;
} flags;
if ( flags.good == 1 ) /* Easy test */
flags.fail = 1; /* Easy set */
flags.good = 0; /* Easy unset */
Compare that to the use of an int variable and bit operations:
Code:
unsigned flags = 0;
if ( ( flags & ( 1U << 1 ) ) == 1 ) /* Not so transparent test */
flags |= ( 1U << 0 ); /* Not so transparent set */
flags &= ~( 1U << 1 ); /* Not so transparent unset */
Of course, bit-fields are 100% non-portable whereas bit twiddling can be made to be portable. Most programmers choose to have the extra flexability and decreased clarity over ease of use, clarity, and no portability.