How it works...

A structure is defined by the name customers, which consists of a few members. The members of the structure are of different data types. A compile-time assert is defined that places a constraint on the size of the customers structure to be of 28 bytes exactly. That means the program will not be compiled if the size of the structure is less than or greater than 28 bytes. The main function simply displays the size of different data types such as int, float, and char. The program also displays the size of the complete customers structure.

The program is compiled using GCC, as shown in the following screenshot. Because the size of the customers structure is exactly the same as that specified in the compile-time assert, the program compiles perfectly and the compileassert.c program is successfully compiled into a .exe file: compileassert.exe. On executing the file, we get the output showing the size of different data types and that of the customers structure, as shown in the following screenshot:

Figure 4.7

After changing the value in the assert function, that is, if the size of the structure does not match the value mentioned in the compile-time assert, we get a compilation error as follows:

Figure 4.8

VoilĂ ! We have successfully implemented compile-time assertions to be able to catch errors early in the system. Now, let's move on to the next recipe!