Use of the Assert () function in C + + + _ function

Source: Internet
Author: User
Tags assert terminates
The stereotype of an Assert macro is defined in <assert.h>, which terminates the execution of the program if its condition returns an error, and the prototype defines:
#include <assert.h>
void assert (int expression);

The role of assert is to calculate the expression expression, 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. Please see the following list of programs BADPTR.C:

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
int main (void)
{
       FILE *FP;
    
       fp = fopen ("Test.txt", "w"),//open a file in a writable manner, and create a file
       assert (FP) with the same name if not present;                           So there's no mistake
       fclose (FP);
    
       fp = fopen ("Noexitfile.txt", "R");//Open a file as read-only, open file Failure
       assert (FP) if not present;                           So here's the error
       fclose (FP);                           The program will never execute here. return
       0;

[Root@localhost error_process]# gcc badptr.c
[Root@localhost error_process]#./a.out
A.out:badptr.c:14:main:assertion ' FP ' failed.

The disadvantage of discarding assert () is that frequent calls can greatly affect the performance of the program and add additional overhead. After debugging, you can disable an assert call by inserting #define NDEBUG before the statement that contains #include <assert.h>, the sample code is as follows:

#include <stdio.h>
#define NDEBUG
#include <assert.h>


Usage Summary and attention matters:

1 Verify the validity of the incoming parameter at the beginning of the function such as:

int resetbuffersize (int nnewsize)
{//
function: Changing buffer size,
//parameter: Nnewsize buffer new length
//return value: Buffer current length// 
Description: Keep original  Information content unchanged     nnewsize<=0 means clear buffer
assert (nnewsize >= 0);
ASSERT (Nnewsize <= max_buffer_size);
...
}

  

2 Each assert checks only one condition, because when multiple conditions are checked, if the assertion fails, it is not intuitive to determine which condition failed, such as:

Not good:

ASSERT (noffset>=0 && noffset+nsize<=m_ninfomationsize);

Good:

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

3 You cannot use statements that alter the environment, because assert only takes effect in debug, and if you do so, you will use the program to run a problem with the actual runtime, such as:

Error:

ASSERT (i++ < 100);

This is because if an error occurs, such as i=100 before execution, then the statement is not executed, and i++ This command is not executed.

That's right:

ASSERT (I < m);
 i++;

4 Assert and subsequent statements should be empty line to form a logical and visual sense of consistency.

5 in some places, assert cannot replace conditional filtering.

Assert is used to avoid obvious errors, rather than handling exceptions. Errors and exceptions are not the same, errors should not occur, and exceptions are unavoidable. C language anomaly can be handled by conditional judgment, and other languages have their own exception handling mechanism. A very simple rule of using Assert is that the first use of a method or function, if used in the middle of a method, requires careful consideration of whether it should be. The beginning of the method has not yet started a functional process, the problem in the execution of a functional process is almost always abnormal.

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.