Explanation of C assertions/static assertions

Source: Internet
Author: User

Assertions can be used as a powerful debugging method or an error diagnosis during program running.
However, assertions are not suitable for various places. server software and embedded programs are generally not applicable. Assertions force the interruption of running programs. For programs such as servers,
It will be a disaster. In addition, assertions will increase the CPU load, and some functions will be called.
Using assertions for debugging is a good choice.
General assertions:
# Ifndef NDEBUG
Assert (conditon );
# Endif
In this way, your assert will detect whether the expression in assert (...) is true when NDEBUG is not defined. If not, the program will be terminated.
However, as a debugging method, assert () is generally not used to judge user input, but to assert that the state of the program at a certain time point must be true. Of course, the method to terminate the program is a bit rude, but it is more effective than continuing to execute the wrong program.
The following are static assertions.
Why use static assertions?
Static assertions can be used to determine program errors during compilation, while common assertions can only exit and generate debugging information when program errors occur.
Static_assert (condition, string_condition );
The first parameter is the expression, and the second parameter is the output information.
Static_assert () is newly added to C ++.
This can be achieved in C:

# Define JOIN (X, Y) JOIN_AGIN (X, Y)
 
# Define JOIN_AGIN (X, Y) X # Y
 
Typedef static_assert (e )\
 
Typedef char JOIN (assert_failed_at_line ,__ LINE ___) [(e )? 1:-1]


From _ Boz From CUG technical blog

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.