C + + assert ()

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 function 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.
The program is then terminated 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 with the same name if it does not exist
ASSERT (FP); So there's no mistake.
Fclose (FP);

fp = fopen ("Noexitfile.txt", "R"),//open a file as read-only, failure to open file if not present
ASSERT (FP); So there's a mistake.
Fclose (FP); The program will never be executed 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.
Has abandoned

The disadvantage of using assert is that frequent calls can greatly affect the performance of your program and add additional overhead.
After debugging, you can disable an assert call by inserting #define NDEBUG (or by adding the parameter-D ndebug at compile time) 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: Change the buffer size,
Parameters: Nnewsize Buffer new length
Return value: Buffer current length
Note: Keep the original information content unchanged nnewsize<=0 to clear the 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

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

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


3 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 into problems when you are actually running
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.
Correct: Assert (I < 100)
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

Article Source: http://www.diybl.com/course/3_program/c++/cppjs/20071111/85534.html

Excerpt from the high quality C + + Programming Guide Page 41-42 ...

The program is generally divided into debug and release versions, and the debug version is used for internal debugging and release versions are available to users.
Assert assert is a macro that works only in the debug version and is used to check for situations where "should not" occur. Example 6-5 is a memory copy function. During the run, if the Assert argument is false, the program aborts (and generally prompts a dialog indicating where the assert was raised).

void *memcpy (void *pvto, const void *pvfrom, size_t size)
{
Assert ((pvto!= null) && (pvfrom!= null)); Using assertions
byte *pbto = (BYTE *) pvto; Prevent change of Pvto address
byte *pbfrom = (BYTE *) Pvfrom; Prevent change of Pvfrom address
while (Size-> 0)
*pbto + + = *pbfrom + +;
return pvto;
}
Example 6-5 copying a block of memory that does not overlap

The assert is not a hastily pieced together macro. In order not to cause differences in the debug and release versions of the program, the assert should not have any side effects. So assert is not a function, but a macro. Programmers can think of assert as a harmless test that can be safely used in any system state. If the program terminates at the assert, not that the function containing the assert has an error, but that the caller has made a mistake, the assert can help us find out why the error occurred.

There is very little more frustrating than the assertion that tracks the program, but does not know the effect of the assertion. You spend a lot of time not trying to rule out mistakes, but just trying to figure out what the mistake is. Sometimes, programmers occasionally design false assertions. So if it's not clear what the assertion checks, it's hard to tell whether the error is in the program or in the assertion. Fortunately, the problem is well solved, just add a clear annotation. This is the obvious thing, but few programmers do. This is like a man in the forest, see the tree nailed a "dangerous" big brand. But what is the danger. The tree is going to fall. There are waste wells. There are beasts. Unless you tell people what "danger" is, it is difficult to play a positive and effective role in this warning sign. Hard to understand assertions are often ignored by programmers and even deleted.

The rule 6-5-1 uses assertions to catch illegal situations that should not occur. Do not confuse the distinction between illegal and erroneous situations, which are inevitable and must be dealt with.
"Rule 6-5-2", at the entrance of a function, uses assertions to check the validity (legality) of a parameter.
"Recommendation 6-5-1", when writing a function, is examined repeatedly and asks: "What assumptions do I intend to make?" "Once you have established the assumptions, use assertions to check the assumptions."
"Recommendation 6-5-2" general textbooks encourage programmers to make error-proofing designs, but keep in mind that this style of programming may conceal errors. When making error proofing design, if "impossible" thing does happen, then use the assertion to alarm.

Elements that should be contained in an Assert macro:

To determine the condition, the position (file, number of rows, etc.) where the current assertion failed, return an error, terminate the program ...

Several typical forms of assert:

VC in the wording:

#define ASSERT (f) \
Do \
{ \
if (!) ( f) && Afxassertfailedline (This_file, __line__)) \
AfxDebugBreak (); \
while (0) \

#define _ASSERT (expr) \
do {if (!) ( Expr) && \
(1 = = _CrtDbgReport (_crt_assert, __file__, __line__, NULL, NULL)) \
_CrtDbgBreak (); } while (0)

The other platform's wording:

# define ASSERT (x) (x) | | (dbg_printf ("Assertion failed (" __file__ ":%d): \"%s\ "\ n", __line__, #x), Break_point (), FALSE)

Original website address: http://hi.baidu.com/uwbadnhctpkopwr/item/1d5d1e1d316c79fcdceeca0a

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.