0

If i declare something like this

struct S{
  unsigned int bit:4;
}

How is it working?

  1. I allocate 2 bytes in memory(size of structure(got this size from here http://en.cppreference.com/w/cpp/language/bit_field) but use only 4 bits of it, and other memory in that structure is wasted.
  2. I allocate only 4 bits, nothing more.

I'm very confused about this and can't find any info about this anywhere.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
bingo157
  • 113
  • 1
  • 2
  • 12
  • Ok, thanks guys, I wasn't sure about that thing, thanks again for help :) – bingo157 Apr 25 '15 at 16:40
  • Fundamentally, you are asking for **at least 4 bits**, the compiler is allowed to allocate those 4 bits in a larger container, such as a 64-bit integer. As long as the compiler supplies you with 4 bits, the compiler conforms to the language. – Thomas Matthews Apr 25 '15 at 18:36
  • @ThomasMatthews so this is the first option, yes? – bingo157 Apr 25 '15 at 18:48
  • Not exactly the first option. The compiler may allocate 2, 4, 8 or more bytes because of the `unsigned int`. – Thomas Matthews Apr 25 '15 at 19:35

3 Answers3

3

When you write

S s;

you allocate sizeof (S) bytes, which seems to be 2 in your case.
The fact that you only use 4 bits of that space does not change the size.

Beta Carotin
  • 1,659
  • 1
  • 10
  • 27
0

You cannot allocate 4 bits. The lowest memory allocation unit is a byte, 8 bits.

However there is no reason to use an unsigned int this would waste even more memory, use an unsigned char.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0

This will allocate 4 bytes of memory and only use 4 bits of it. Bit fields are required to take up all the space for the type they are declared as, even if it isn't all used.

If you want to use the memory more efficiently you could do this:

struct S{
    unsigned char bit : 4;
};

and it would only allocate a byte.

Also sizeof(unsigned int) is usually 4 bytes so sizeof(S) will be at least 4 bytes.

phantom
  • 3,292
  • 13
  • 21
  • 1
    Whether it allocates 8, 4, or 2 bytes for an integer is platform dependent. The size of an `int` is minimally 16 bits to satisfy the range requirements. Most compilers use the processor's word size for an `int`, which is 8 bytes on a 64-bit system, 4 bytes on a 32-bit system and 2-bytes on 16 and 8-bit systems. The is no maximum size limit. – Thomas Matthews Apr 25 '15 at 18:34