Get the App
SLTechnology News&Howtos  ›  Development  › 

The example usage of assert () function in C++

Shulou Source: shulou.com Published: 2022-06-03 17:30:27 09月17日 Update

This article mainly explains the "example usage of the assert () function in C++". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn the example usage of the assert () function in C++.

1. Brief introduction

The prototype of the assert macro is defined in to terminate program execution if its condition returns an error.

Prototype definition:

# include void assert (int expression)

The role of assert is to first evaluate 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. Take a look at the following program listing badptr.c:

# include # include # include 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 assert (fp) if it does not exist; / / so there is no error fclose (fp) here Fp = fopen ("noexitfile.txt", "r"); / / Open a file as read-only. If it does not exist, it fails to open the file assert (fp); / / so there is an error fclose (fp); / / the program will never be executed here to 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 reason for abandoning the use of 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 # define NDEBUG before the statement that contains # include, as shown in the sample code:

# include # define NDEBUG#include 2. Summary of usage and points for attention:

1) verify the validity of the passed parameters at the beginning of the function, such as:

Int resetBufferSize (int nNewSize) {/ / function: change buffer size, / / Parameter: new length of nNewSize buffer / / return value: current length of buffer / / description: keep the original information content unchanged nNewSize= 0); assert (nNewSize= 0 & & nOffset+nSize= 0); assert (nOffset+nSize

Tags: Functions conditions programs errors instances examples files statements contents functions methods buffers problems processing learning testing buffering functions information prototypes Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Shulou Information OPPO Reno Shulou Technology Apple