Preprocessing function debugging assert and NDEBUG

The header #include <cassert>
assert is a preprocessor macro that uses an expression as its condition.

assert(expr);

Assert is a bit like a checkpoint. It checks the identity (expr) of the program flow that passes through this checkpoint. The defender picks up your ID and lets you pass if you are satisfied. If you don't meet it, the program will be terminated by an alarm. By default, assert is enabled, and you can disable it in the following two situations:

  • By -Dpassing the NDEBUG macro at compile time
  • The source file #definedefines the NDEBUG macro

In general, assert should be used in situations that are truly impossible, only for debugging , not to replace runtime logic checks. Of course, the NDEBUG macro can also be used to define code that runs only during debugging:

#ifndef NDEBUG
	//有点绕,如果没有定义不调试,那就是调试
	//我想要在调试时执行的代码
#endif

When there is no definition of no debugging (that is, debugging), we can print some information: __func__ __FILE__ __TIME__ __DATE__(No need to count, it is a double underscore). These literal constants can be output through cerr.

Experience of using assert provided by others:

  • Check the validity of the incoming parameters at the beginning of the function
  • Each assert only checks one condition, because when multiple conditions are checked at the same time, if the assertion fails, it is impossible to intuitively judge which condition failed.
  • The statement that changes the environment cannot be used, because assert only takes effect in DEBUG. If you do this, you will encounter problems when the program is actually running. Error: assert(i++ <100):
  • Assert and the following statement should be left blank to form a logical and visual sense of consistency

Several principles with assertions:

  • Use assertions to catch illegal situations that shouldn't happen. Do not confuse the difference between illegal situations and error situations. The latter is inevitable and must be dealt with.
  • Use assertions to confirm the parameters of the function.
  • When performing error-proof programming, if something "impossible to happen" does happen, an assertion should be used to alarm.

[1] https://www.runoob.com/w3cnote/c-assert.html

Guess you like

Origin blog.csdn.net/weixin_39258979/article/details/114106791