Assertions in C/C++
What is Assertion?
Assertions are the set of codes where we put some expression or condition to check whether the condition is true or not or to check whether the expression exists or not.
The 'assert()' keyword is used in assertion where we put the expression for the evaluation. Assertion's expression can be related to the assumption of a programmer for any variable or any statement of the code.
For example, if we want to check whether the value of any variable is changed to some other value during the program, then we can make assumptions with the help of assertion.
C Example 1:
In the above code, we have a variable which is initialized with the value 65. After that, we have added 6 to this variable, so now its value is 71. Now we have subtracted 45 from it, so now the value is 26.
Now in the assert condition, we put the expression that if the value of the variable is equal to 45 or not. So it will return 0 since it is a false condition, and our program will be aborted, and further lines of code will not run.
C Example 2:
In the above code, we have put a condition in the assertion that if the variable is equal to 26, which is true and it will return 1. So the following line of the code will run without any problem.
Since assertion is quite similar to error handling, where if an error exists then we can do error handling and terminate our program; otherwise, the rest of the code will run without any problem.
But there are a lot of differences between assertion and normal error handling:
We can also ignore the assertion at the compile time in the code if it is present. We have to import the preprocessor directive NDEBUG.
C Example 3:
In the above, the value of the variable is 26, and the condition in the assertion is false. Still, the program will not be terminated because we have imported the preprocessor directive NDEBUG and assertion is ignored successfully.
There is also the concept of static assertion, which is run at compile time, whereas assert() is used at run time only. The static assertion is only possible in C++. It is not present in C.
The static assertion is checked at the compile time, so it will give the compile time error representing that the expression in the static assertion is not correct. We have normal assertion present also in this code, but it will be checked at the runtime only.