Use of the C language assert

Source: Internet
Author: User

Assert

Role

The key place in the program can be asserted by asserting this macro. If the assertion is not true, the program stops and the standard error outputs a specific error message.
However, in actual combat, the program stops directly is very bad phenomenon, so the assertion is only used in the debugging program.













NDEBUG macro

In order to facilitate the use of assert in debugging, and when it is not necessary to easily stop the work of the assert, so there is a Ndebug macro to specify the behavior of the assert. If you define this macro, the Assert does not work.

#ifdef Ndebug
#define ASSERT (x) ((void) 0)
#else
...








features of the header file
assert.h header files are different from other header files and do not have idempotent features.
idempotent is the same effect that contains the file once to many times.


However, the Assert.h file contains multiple times, but not necessarily the same.

The definition of the original assert macro was canceled at the outset

so open the assertion to write#undef Ndebug#include <assert.h>
turn off assertions to be written#define NDEBUG#include <assert.h>



Test
#include <stdio.h> #include <stdlib.h> #define ndebug#include <assert.h>void T1 (void) {    int i = 0;< C1/>assert (i = = 0);    assert (i = = 1);} #undef ndebug#include <assert.h>void T2 (void) {    int j = 0;        assert (J = = 0);    assert (J = = 1);} #define Ndebug#include <assert.h>int Main (void) {    int i = 1;    assert (i = = 0);    T1 ();    printf ("Hello world\n");    T2 ();}


When the T1 function starts, the assertion is canceled, so the execution T1 does not stop. The T2 function starts with an assertion, so the final T2 stops at the j==1 sentence. The main function, although asserted as false, does not stop when the assertion is canceled at the beginning.



The output is:











Use of the C language assert

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.