0

I am reading the book Data Structures and Algorithms in C++ 4th Edition by Adam Drozdek, and I encountered the following code. My question is what does the colon do in unsigned int successor : 1;. I found an answer saying that the colon makes the successor take only one bit. But I know that boolean variables take multiples of bytes since the variable must be addressable. If the successor takes only one bit, how can it be addressable?

template<class T>
class ThreadedNode {
    public:
         ThreadedNode() { 
             left = right = 0; 
         }
         ThreadedNode(const T& e, ThreadedNode *l = 0, ThreadedNode *r = 0) {
             el = e; left = l; right = r; successor = 0; 
         }
         T el;
         ThreadedNode *left, *right;
         unsigned int successor : 1;
};
HoiM
  • 81
  • 6
  • 2
    Means somebody has no idea what they are doing. Bitfield in this place is absolutely useless. – SergeyA Dec 19 '17 at 21:33

1 Answers1

1

This is known as a Bit Field. The expression unsigned int successor : 1; declares an unsigned int named successor of which you expect to use only 1 bit.

The behavior of using a bit field in a way that would require the use of more bits than was specified is implementation-defined behavior. It's also impossible to get a pointer or non-const reference to a bit field, since they do not necessarily begin at the beginning of a byte.

Bit fields allow compilers to reduce the size of a type in some cases by packing compatible bit fields together. Bit fields are non-binding in terms of size reduction and are only an opportunity for the compiler.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87