The principle of C + + assert () assertion mechanism and the use

Source: Internet
Author: User
The MSDN text says:

Evaluates an expression and if the result is false, prints a diagnostic message and aborts the program.

(Judging an expression, if the result is false, output a diagnostic message and abort the program.) )

void assert (      int expression   );

Parameters: expression (including pointers) that evaluates to nonzero or 0. (expression "including pointer" is not 0 or 0)

Principle: The function of assert is to calculate expression expressions, if its value is false (that is, 0), then it first prints an error message to stderr, and then terminates the program by calling abort.

MSDN Sample Program;

CRT_ASSERT.C  //compile with:/C  #include <stdio.h>  #include <assert.h>  #include < string.h>    void analyze_string (char *string);   Prototype    int main (void)  {     char  test1[] = "abc", *TEST2 = NULL, test3[] = "";       printf ("Analyzing string '%s ' \ n", test1); Fflush (stdout);     Analyze_string (test1);     printf ("Analyzing string '%s ' \ n", test2); Fflush (stdout);     Analyze_string (test2);     printf ("Analyzing string '%s ' \ n", test3); Fflush (stdout);     Analyze_string (TEST3);  }    Tests a string to see if it is NULL,   //empty, or longer than 0 characters.  void Analyze_string (char * string)  {     assert (string! = NULL);        Cannot be NULL     assert (*string! = ');       Cannot be empty     assert (strlen (string) > 2);  Length must exceed 2  }

Output results

Analyzing string ' abc '  analyzing string ' (null) '  assertion failed:string! = null, file assert.cpp, line    AB Normal program termination

Summary of Usage:

1) Verify the legitimacy of incoming parameters at the beginning of the function
Such as:

int resetbuffersize (int nnewsize)
{
Function: Change buffer size,
Parameter: Nnewsize buffer new length
Return value: Buffer current length
Note: Keep the original information content unchanged nnewsize<=0 means clear buffer
ASSERT (nnewsize >= 0);
ASSERT (Nnewsize <= max_buffer_size);

...
}

2) Each assert examines only one condition, because when multiple conditions are checked, if the assertion fails, it is not possible to visually determine which condition failed

Bad: Assert (noffset>=0 && noffset+nsize<=m_ninfomationsize);

Good: Assert (noffset >= 0);
ASSERT (Noffset+nsize <= m_ninfomationsize);


3) You cannot use a statement that alters the environment, because assert only takes effect in debug, and if you do, you will use the program to run into problems when it is actually running


Error: Assert (i++ < 100)
This is because if there is an error, such as i=100 before execution, then this statement will not be executed, then i++ This command will not be executed.
Correct: Assert (i < 100);
i++;


4) Assert and subsequent statements should be empty lines to create a logical and visual sense of consistency

5) In some places, assert cannot replace conditional filtering

Assert is only valid in debug versions and is ignored if compiled to release version. (in C, assert is a macro instead of a function), using Assert "assert" is easy to output a program error at debug time.
The function of assert () is similar, it is a function specified in the ANSI C standard, and an important difference between it and assert is that it can be used in release version.

The disadvantage of using assert is that frequent calls can greatly affect the performance of the program and add additional overhead.
After debugging, you can disable the Assert call by inserting the #define NDEBUG before the statement that contains # include <assert.h>, as shown in the following example code:
#include <stdio.h>
#define Ndebug
#include <assert.h>

After joining the # define NDEBUG, the first example above shows the following output:

Analyzing string ' abc '  analyzing string ' (null) '  analyzing string '

A frequently used topic in an interview:

The known memcpy functions are: void* memcpy (void *dest, const void* SRC, size_t count) where dest is the destination pointer, and SRC is the source pointer. If you do not call the C++/C memcpy library function, write memcpy.

void* memcpy (void *dst, const void *SRC, size_t count)      {          //Security check      assert ((DST! = null) && (src! = null) );            unsigned char *pdst = (unsigned char *) DST;          Const unsigned char *psrc = (const unsigned char *) src;            Prevent memory duplication      assert (! ( PSRC<=PDST && pdst<psrc+count));          ASSERT (! ( PDST<=PSRC && psrc<pdst+count));            while (count--)          {              *pdst = *psrc;              pdst++;              psrc++;          }          return DST;      }

The above is the C + + assert () assertion mechanism and the use of content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.