ASSERT () Function Usage Summary

Source: Internet
Author: User
Tags terminates

The prototype of an Assert macro is defined in <assert.h>, and its function is to terminate the execution of the program if its condition returns an error, and the prototype defines:

 #include  Span style= "font-size:12px!important; Line-height:1.5!important "><   >    void   assert ( int   expression);  

 The function of an assert is to evaluate expression expressions, if the value is False (that is, 0), then it prints an error message to stderr and then terminates the program by calling abort.

Take a look at the following program listing 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 it does not exist;                           So there's no error here       . fclose (FP);           fp = fopen ("Noexitfile.txt", "R");//Opens a file in a read-only manner, and if it does not exist, the file fails       assert (FP);                           So here's the error       fclose (FP);                           The program will never execute here to       return 0;}

[Email protected] error_process]# gcc badptr.c
[Email protected] error_process]#./a.out
A.out:badptr.c:14:main:assertion ' FP ' failed.

  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>#defineNdebug#include<assert.h>


Usage Summary and Precautions:

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//Description: Keep the original information content unchanged     nnewsize<=0  Represents the purge 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 , such as:

Not good:

assert (nOffset  >=  0    Span style= "font-size:12px!important; Line-height:1.5!important ">&&   +  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, such as:

Error:

assert (I+ +<);

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.

That's right:

<); I+ +;

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

5) In some places, assert cannot replace conditional filtering.

here are a few principles for using assertions:

(1) Use assertions to catch illegal situations that should not occur. Do not confuse the difference between the illegal situation and the wrong situation, the latter being inevitable and must be dealt with.

(2) Use assertions to confirm the parameters of the function.

(3) When writing a function, repeat the examination, and ask yourself: "What assumptions do I intend to make?" "Once you have identified theassume that an assertion is used to check the assumptions.

(4) General textbooks encourage programmers to design for error-proof, but keep in mind that this style of programming conceals errors. When error-proof programming occurs, an assertion is used to alert you if the "impossible" thing does happen.
  
ASSERT () is a macro that is used frequently when a debugger is run, and it calculates the expression in parentheses when it runs, and if the expression is False (0), the program reports an error and terminates execution. If the expression is not 0, the following statement continues.  This macro usually turns out that there is clearly illegal data in the program, and if a termination procedure is used to avoid serious consequences, it is also easy to find errors.

assert is only valid in debug versions and is ignored if compiled to release version.

The better place to use assert in your program:

(1) NULL pointer check. For example, a null pointer check is performed on the parameters of a function. You can use this: ASSERT (pointer! = NULL), and the resulting error will look like this: assertion ' pointer! = ((void *) 0) ' failed. This way, when a null pointer appears, your program exits and gives you a good error message.

(2) Check the value of the function parameter. For example, if a function can only be called when one of its parameter foo is positive, you can write this at the beginning of the function: Assert (foo > 0), which will help you detect the incorrect use of the function, which also gives the source reader a clear impression that there is a limit to the parameter value of the function.


ASSERT () Function Usage Summary

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.