Reputation: 513
I am looking into the code written by other members and I came across the code shown below:
struct myType
{
int myInt : 1;
int reserved : 31;
};
What is 1 and 31 stands above and when above notation is used?
Upvotes: 1
Views: 159
Reputation: 38173
These are bit fields. This code means, that myInt
is just one bit and reserved
is 31 bits
For example, on my machine
struct a
{
int asd : 1;
int b : 2;
};
std::cout << sizeof( a );
prints 4
(it's platform dependent). In you're example, the exact size of the struct is 32bits, but it's possible the actual size to be different - depends on the alignment
Upvotes: 1
Reputation: 399833
Those are bit fields, the number after the colon specifies the width, in bits, reserved for that field. They are often used when trying to conserve space, or when trying to map an external (think hardware-owned) register that has bitfields. Note that packing and endianness affect how the bits are layed out in memory, so they're not to be used if portability is important.
Note that it's a very bad idea to use signed bit fields with very small sizes, such as 1. Since one bit is needed for the sign, no bits are left for the actual value which is generally not a very good situation. Using unsigned int myUnsigned : 1
fixes this.
Upvotes: 4