Types of assert
Explore the use of assert and static assert statements in D programming to validate assumptions within code. Understand how assert checks logical expressions at runtime, triggering errors when assumptions fail, while static assert enforces correctness at compile time, preventing faulty code from compiling. This lesson helps you grasp critical tools for maintaining program stability and correctness.
We'll cover the following...
Need for assert
In the previous chapter, we have seen how exceptions and scope statements are used toward program correctness. assert is another powerful tool to achieve the same goal. assert ensures that the certain assumptions that the program is based on are valid.
It may sometimes be difficult to decide whether to throw an exception or to call assert. I will use assert in all of the examples below without much justification. We will look at the differences later in the chapter.
Although not always obvious, programs are full of assumptions. For example, the following function is written under the assumption that both age parameters are greater than or equal to zero:
Although it may be invalid for the program to ever have an age value that is negative, the function would still produce an average, which may be used in the program unnoticed, resulting in the program continuing with incorrect data.
As another example, ...