Using bit fields in a struct
In structures, we can use bit fields to denote what size we want the structure to be. As well as this, it is also important to understand what size a struct actually takes.
Getting ready
You need a Windows machine and a working copy of Visual Studio. No other prerequisites are required.
How to do it…
In this recipe, we will find out how easy it is to use bit fields to find the size of a struct. Add a source file called Source.cpp
. Then add the following code to it:
#include <iostream> struct Type { int a; unsigned char c[9]; unsigned b; float d; }; struct Type2 { int a : 2; int b : 2; }; int main() { std::cout << sizeof(Type)<<std::endl; std::cout << sizeof(Type2); int a; std::cin >> a; }
How it works…
As you can see, in the example we have assigned a struct of int, a char array, an undefined unsigned variable, and a float. When we execute the program, the output should be the size of both the structures...