assert
Assert is a run-time assertion that is used to discover errors during a run, not to find errors early in the compilation period,
Also does not have the mandatory, also not to improve the readability of compiling information, since it is run-time check, the performance is of course
Have an impact, so often in the release version, theassert will be turned off.
The key to assert is to judge the true logic of expression, and if false, it will be played on the stderr .
Print an error message containing the expression, file name, line number, and then call abort to end the entire program.
#include <iostream>#include<assert.h>using namespacestd;Char* MYSTRCPY (Char*dest,Const Char*src) {assert (dest); assert (SRC); while(*dest++ = *src++);} intMainintargcChar*argv[]) { //Char buf[1024]; char * p = NULL; //mystrcpy (buf,p); //cout<<buf<<endl;FILE *FP = fopen ("AA.C","R"); ASSERT (FP); return 0;}
Static_assert
Static_assert this keyword is used to make assertions during compilation, so it is called a static assertion. Its syntax is simple: static_assert ( constant expression, hint string
If the value of the first parameter constant expression is true (true static_assert Do nothing, as if it does not exist, or it will produce a compile error, the error location is the static_assert statement, the error is the second parameter prompt string.
Use static_assert
Static_assert can be used in a global scope, in a namespace, in a class scope, in a function scope, with almost unlimited use.
When the compiler encounters a static_assert statement, it usually calculates its first argument as a constant expression immediately, but if the constant expression relies on some template arguments, then the calculation is deferred until the template is instantiated, which makes it possible to check the template parameters.
#include <iostream>using namespaceStd;static_assert (sizeof(void*) ==4,"64-bit code generation is not supported.");//The static_assert is used to ensure that the compilation is performed only on 32-bit platforms and does not support the 64-bit platform, whichStatement can be placed///at the beginning of the file, this can be checked as early as possible to save compilation time in case of failure. Template<typename T, TypeName u>intMy_bit_copy (t& A, u&b) {Static_assert (sizeof(a) = =sizeof(b),"parameters must have same width");} intMainintargcChar*argv[]) { intAfloatb; My_bit_copy (A, b); CharC; My_bit_copy (A,C); return 0;}
C++11 Assert/static_assert