Why use assertions?
First of all to figure out why to use assertions, not to see others code, you follow the fashion to use a! In effect, an assert assertion can be replaced with an if statement, so why not replace the assertion with an if statement? In general, an if statement is an error that can be handled logically, and assertions are used to handle situations that should not occur.
What is the situation that should not be sent? This to distinguish the source of data: 1, the data from the system (sub-program, sub-module calls) 2, the data from the external system (external devices such as keyboard input, serial data reading, network data reading). Data from internal sources, we can not go through the conventional testing methods to verify, when the assertion is used.
Of course, if you want to use the IF statement and no one said you are wrong, but a large number of if statements appear in the source code, it will lead to bloated codes, reduce readability, in addition, will produce less compact code, affecting efficiency.
In the early stages of program development, the code farmer ignores the legality of the call parameters between the programs, which can be used to prevent accidents, and as the program enters Release edition, Ndebug can be defined to invalidate the assertion. The following is Ndegbu's handling code for assert.
#ifdef Ndebug #define assert (expr) (static_cast<void> (0))#else ... #endif
How do I use assertions?
The Assert macro is provided in the standard library. It is declared in the library file <cassert> that it can test the logical expression in the program, and if the specified logical expression is False,assert () terminates the program and displays the diagnostic message. A close assertion uses the # define NDEBUG, which ignores all assertion statements in the conversion unit. And this directive only works before # include <cassert>. Examples are as follows:
#include <iostream> #define NDEBUG //Close all assertions that must be placed in # include <cassert> before # include <cassert>using namespace Std;int main () {int a = ten, B = 2;//Use assertion, if False in assert (), the program terminates exit assert (a < b); cout << a << b < < Endl;return 0;}
About the use principle of assertions
Finally, share the recommendations in the Code encyclopedia for assertion Usage:
1, using error handling code to deal with the expected occurrence of the situation, with assertions to deal with the situation should never happen;
2. Avoid putting the code that needs to be executed into the assertion;
3, using assertions to annotate and verify the pre-conditions and post-conditions;
4, for the high robustness of the code, you should first use the assertion to deal with errors;
C + + Assertion