Assert.h

1

assert.h is a header file in the C standard library. It defines the C preprocessor macro and implements runtime assertion in C. assert.h is defined in ANSI C as part of the C standard library. In the C++ programming language, assert.h and are available; both are functionally equivalent.

Use

The macro implements runtime assertion. If the expression within it is false, the macro will print a message to and call , defined in stdlib.h. The message includes the source filename and the source line number from the macros FILE and LINE, respectively. Since C99, the name of the function the assert statement is included as (FUNC) and the expression itself. In ANSI C, the expression in the macro is defined as signed integer, although any expression that can be implicitly cast to a signed integer may be used. In C99, the macro explicitly allows any scalar type. Two common uses of the macro are to assert that a pointer is not null and to ensure that an array index is in-bounds. Below is a program using the macro. This program will always evaluate as false, as is a null pointer and does not point to a valid memory location: Upon compiling the program and running it, a message similar to the following will be output: The definition of the macro changes depending on the definition of another macro,. If is defined as a macro name, the macro is defined as, thus resulting in the macro not evaluating the expression. The use of may affect the overall behavior of a program if one or more statements contain side effects, as these statements are not evaluated. The macro does not include an error message. However the comma operator can be used to add it to the printed expression, as in.

static_assert

The static_assert macro, added in C++11, serves a similar purpose to the assert macro. Unlike the assert macro, static_assert runs at compile-time rather than at runtime. The original implementation used template hacks. The macro takes in a constant expression that can be converted into a Boolean and a string literal; if the expression fails, the string literal is returned, otherwise, the macro has no effect. In C++17, this assertion failure message was made optional, and the subsequent message is omitted if not specified. In C11, the functionally equivalent declaration _Static_assert was added. assert.h defines static_assert as an alias for _Static_assert to ensure parity with C++. In C23, _Static_assert was renamed to static_assert and the string literal argument was made optional. Gnulib defines static_assert for platforms that do not use C11 and does not require to be included.

Citations

This article is derived from Wikipedia and licensed under CC BY-SA 4.0. View the original article.

Wikipedia® is a registered trademark of the Wikimedia Foundation, Inc.
Bliptext is not affiliated with or endorsed by Wikipedia or the Wikimedia Foundation.

Edit article