Assertions are something that has been done very early, and can only be used with the introduction of the Cassert header file. Often assert is used to check for behavior that is not possible, to ensure that the developer at the beginning of the debugging phase of the early detection of "impossible" events really happened, if it does occur, then the logic of the Code has problems. The best thing is that the assertion only takes effect in debug, so there is no efficiency impact on the release version.
#include <iostream><cassert>usingnamespaceint Main ( ) { int; A ); System ("pause"); return 0 ;}
The above code shows that you confirm that I must not be equal to 22 here, if it is actually 22, then the program will be ruthlessly abort, and report the source file and line number of the problem (using the Magic constants __file__ and __line__), help to locate the problem in a timely manner.
Assertion has a problem, is bound to abort, forcing the entire program to quit and cause debugging can not continue, like this, after the problem, we know the problem of the line number, but we need to manually set a breakpoint on the line above the row, re-start debugging to be able to check the status of the individual variables when the problem occurs. Moreover, sometimes the problem is not so easy to reproduce, so there is a problem that can not reproduce the error and then check the status.
So, we can write a similar macro ourselves to solve this problem, and we want to trigger a breakpoint trap gate interrupt instead of calling abort when the assertion is violated, so that the program pauses when the assertion is violated and waits for the programmer to check the current state for any exceptions.
The following is an implementation in Visual C + +.
#include <iostream>#include<cassert>using namespacestd;#define_assert (x) if (! ( x)) __asm {int 3};intMain () {inti = A; //assert (I! =);_assert (i! = A); System ("Pause"); return 0;}
The above defines a macro, the name of course can be taken, in fact, one thing is to check the assertion, and then if the assertion result is False (0), then call inline assembly instruction int 3 into a debug interrupt.
In the 2011 C + + Standard, there was a static assertion (Static_assert) syntax, the so-called static assertion, which is the assertion that can be checked at compile time, Static_assert is the standard syntax for C + + and does not require a reference to a header file. Another benefit of static assertions is that you can customize the compilation error message when the assertion is violated.
#include <iostream>usingnamespaceint main () { const int; A " I equals to " ); System ("pause"); return 0 ;}
This code will fail to compile because the value of I violates the static assertion.
The limitation of a static assertion is that the assertion itself must be a constant expression, and if such i is not a constant, the static assertion is not syntactically compliant.
C + + assertions vs. static assertions