Use of assert () Functions

Source: Internet
Author: User

The assert macro prototype is defined in <assert. h>. If its condition is false, terminate the program execution. The prototype is defined. Assert () is a macro that is often used to debug the program, when the program is running, it calculates the expressions in parentheses. If the expression is false
(0), the program will report an error and terminate the execution. If the expression is not 0, execute the following statement. This macro often used to determine whether there was clearly illegal data in the program. If the program was terminated, it would not cause serious consequences, but also facilitate searching for errors:

# Include <assert. h>

Void assert (INT expression );

Assert is used to calculate the expression. If its value is false (that is, 0), It prints an error message to stderr first,

Then, call abort
To terminate the program running.

See the following program list 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 writable mode. If it does not exist, create a file with the same name.

Assert (FP); // so there will be no error

Fclose (FP );

Fp = fopen ("noexitfile.txt", "R"); // open a file in read-only mode. If it does not exist, the file fails to be opened.

Assert (FP); // an error occurs here

Fclose (FP); // the program will never be executed here

Return 0;

}

[Root @ localhost error_process] # gccbadptr. c

[Root @ localhost error_process] #./A. Out

A. Out: badptr. C: 14: Main: assertion 'fp' failed.

Abandoned

 

The disadvantage of using assert is that frequent calls will greatly affect program performance and increase additional overhead.

After debugging, you can insert # definendebug before the statement that contains # include <assert. h>.
To disable assert calls. The sample code is as follows:

# Include <stdio. h>

# Define ndebug

# Include <assert. h>

 

Usage summary and precautions:

1) Check the validity of input parameters at the beginning of the Function

For example:

Int resetbuffersize (INT nnewsize)

{

// Function: Change the buffer size,

// Parameter: nnewsize
New Buffer Length

// Return value: Current Buffer Length

// Note: keep the original information unchanged. nnewsize <= 0 indicates clearing the buffer.

Assert (nnewsize> = 0 );

Assert (nnewsize <= max_buffer_size );

}

2) Each assert only tests one condition, because when multiple conditions are verified simultaneously, if the assert fails, it is impossible to intuitively determine which condition fails.

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

Good: assert (noffset> = 0 );

Assert (noffset + nsize <= m_ninfomationsize );

3) You cannot use statements that change the environment, because assert takes effect only on Debug. If so, problems will occur when the program is actually running.

Error: assert (I ++ <100)

This is because if an error occurs, for example, I = 100 before execution, this statement will not be executed, and the I ++ command will not be executed.

Correct: assert (I <100)

I ++;

4) assert and the following statement should be empty for logical and visual consistency.

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

 

 

Assert
Assert should not produce any side effects. So assert
Not a function, but a macro. Programmers can regard assert as a harmless testing method that can be safely used in any system status.

There are few more frustrating things than the assertions that trace the program, but do not know the role of the assertions. It takes you a lot of time not to exclude errors, but to find out what the error is. Sometimes, programmers occasionally design wrong assertions. Therefore, if you do not know what the assertions check, it is difficult to determine whether the errors appear in the program or in the assertions. Fortunately, this problem is well solved by adding clear notes. This is obvious, but few programmers do this. This is like a person in the forest, seeing a "dangerous" big sign on the tree. But what is the danger? Will the tree fall? Is there a waste well? Is there a beast? Unless you tell people what danger is, this warning board cannot play a positive and effective role. Incomprehensible assertions are often ignored or even deleted by programmers.

The following principles Use assertions:

(1) Capture exceptions that should not occur with assertions. Do not confuse the differences between illegal and wrong situations. The latter must exist and be handled.

(2) Use assertions to confirm the function parameters.

(3) When writing a function, you should repeat it and ask yourself: "What assumptions do I plan to make ?" Once

Suppose that we need to use assertions to check the assumptions.

(4) In general textbooks, programmers are encouraged to design error-proof programs, but remember that such programming style will conceal errors. When programming against errors, if "impossible to happen" does happen, Use assertions to trigger an alarm.

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.