An analysis of the use of Assert in C language (turn)

Source: Internet
Author: User
Tags assert

Original address: http://www.jb51.net/article/39685.htm

The following is an introduction to the use of Assert in C language, the need for friends can refer to.

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 <assert.h>
void assert (int expression);
The function of assert is to evaluate expression expression First, if its value is false (that is, 0), then it first prints an error message to the standard error stream stderr , and then terminates the program by calling abort . Otherwise, assert () has no effect. Macro assert () is generally used to confirm the normal operation of the program, where the expression construction is not a mistake for truth. After debugging is complete, you do not have to remove the ASSERT () statement from the source code because the macro ndebug definition is empty.
Take a look at the following program listing BADPTR.C:

#include <stdio.h>#include<assert.h>#include<stdlib.h>intMainvoid) {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 existASSERT (FP);//so there's no mistake here .fclose (FP); FP= fopen ("Noexitfile.txt","R");//Open a file in a read-only manner and open it if it does not existASSERT (FP);//so there 's a mistake.Fclose (FP);//The program will never be executed here.       return 0;}

Macro Name: Assert
Function: Test a condition and possibly terminate the program
Usage: void assert (int test);
program Example:

#include <assert.h>#include<stdio.h>#include<stdlib.h>structITEM {intkey; intvalue;};/*Add item to list, make sure list was not null*/voidAddItemstructITEM *itemptr) {Assert (Itemptr!=NULL); /*Add Item to list*/}intMainvoid) {additem (NULL); return 0;}

An analysis of the use of Assert in C language (turn)

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.