0

Why is this code:

#include <iostream>
struct S {
    unsigned char a:6, b:6, c:6, d:6;
};
    int main(int argc, char *argv[]) {
    std::cout << sizeof(S);
    return 0;
}

returning 4? Shouldn't it have a size of 4 x 6 = 24b = 3B? In contrast, this code:

struct S { unsigned char a:4, b:4, c:4, d:4; };

returns a 2, while this one:

struct S { unsigned char a:4, b:4, c:4, d:4, e:4, f:4; };

returns a 3...

Stefan Stanković
  • 628
  • 2
  • 6
  • 17
  • @YSC Alright, I didn't know how to phrase the question. I'll look over there. Thanks. – Stefan Stanković Nov 10 '17 at 14:12
  • 1
    Bit fields do not guarantee that the members' sizes will be exactly the bit counts you provide. Neither is the size of a type constrained to be exactly the sum of it's members. – François Andrieux Nov 10 '17 at 14:12
  • @YSC So, the answer is - it's up to compiler? – Stefan Stanković Nov 10 '17 at 14:21
  • @FrançoisAndrieux So, even though the compiler calculates the other 2 without padding, it adds padding the first one? – Stefan Stanković Nov 10 '17 at 14:25
  • @underscore_d You should vote to close with that duplicate, so it will be included in the duplicates if this question gets closed. – François Andrieux Nov 10 '17 at 14:27
  • @underscore_d: That, however, is a **C** question, while this one is labeled C++... (The answer is identical, but we also *keep* bugging people about not labeling a question both C and C++...) ;-) – DevSolar Nov 10 '17 at 14:27
  • @DevSolar: Some questions are apt to serve both, and I don't think unrelated annoyance at badly tagged questions justifies us denying that. François: I did. – underscore_d Nov 10 '17 at 14:29

1 Answers1

1

From CppReference: Bit Fields:

The following properties of bit fields are implementation-defined:

  • [...]
  • Everything about the actual allocation details of bit fields within the class object

    • For example, on some platforms, bit fields don't straddle bytes, on others they do

So yes, it's implementation-defined (i.e., up to the compiler).

So, even though the compiler calculates the other 2 without padding, it adds padding the first one?

Yes, because in the first case, values would "straddle" byte borders if not padded, while in the other two examples, they don't.

Again, this is implementation-defined and could be handled differently on another platform, a different compiler on the same platform, or even a different version of the same compiler.

DevSolar
  • 67,862
  • 21
  • 134
  • 209