Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type of bit-field members

Tags:

c++

c

bit-fields

Theoretically, we have two options to chose the type of a bit field member:

  1. The type of the underlying type.
  2. The smallest type the number of bits fits in.

So what is the actually the type of bit-field members (I couldn't find so far hints in the standard – C and C++ alike) and is there any difference in between C and C++?

Although being aware that a specific compiler is not the reference, I tried to get at least some hints via C++ function overloads and typeid operator :

#include <typeinfo>
struct S
{
    unsigned int n4  :  4;
    unsigned int n12 : 12;
};

void f(unsigned char)
{
    std::cout << "uc" << std::endl;
}

void f(unsigned short)
{
    std::cout << "us" << std::endl;
}

void f(unsigned int)
{
    std::cout << "ui" << std::endl;
}

int main(int argc, char* argv[])
{
    S s; s.n4 = 0; s.n12 = 0;
    f(s.n4);
    f(s.n12);
    std::cout << typeid(s.n4).name() << std::endl;
    std::cout << typeid(s.n12).name() << std::endl;
    std::cout << typeid(unsigned char).name() << std::endl;
    std::cout << typeid(unsigned short).name() << std::endl;
    std::cout << typeid(unsigned int).name() << std::endl;
    return 0;
}

Output (GCC 5.4.0 under linux) was totally surprising and – in my eyes at least – contradicting:

ui
ui
h
t
h
t
j

So if type, according to typeid operator, is unsigned char and unsigned short respectively, why is unsigned int selected during overload resolution? Possibly even a GCC bug?

Addendum: GCC 8.1 (linux) still exhibits the same behaviour.

like image 864
Aconcagua Avatar asked Oct 30 '22 09:10

Aconcagua


1 Answers

From C++ standard § 10.3.10.1 (class.bit):

The bit-field attribute is not part of the type of the class member.

(I must have overlooked this phrase from the standard when posting the question...)

So the standard is clear about the type of a bit-field member, it is equal to the underlying type.

Thanks to Davis Herring for giving me the appropriate hints.

like image 56
Aconcagua Avatar answered Nov 15 '22 07:11

Aconcagua