Saturday, December 31, 2016

C Assertion

Run Time Assertions:

In C, assertions are implemented with the standard assert macro. The argument to assert must be true when the macro is executed, otherwise the program aborts and prints an error message. For example, the assertion

assert( size <= LIMIT );

will abort the program and print an error message like this:

Assertion violation: file limit.c, line 34: size <= LIMIT

if size is greater than LIMIT.

The simplest and most effective use of assertions is as preconditions-that is, to specify and check input conditions to functions. Two very common uses are to assert that:
1. Pointers are not NULL.
2. Indexes and size values are non-negative and less than a known limit.

By default, ANSI C compilers generate code to check assertions at run-time. Assertion-checking can be turned off by defining the NDEBUG flag to your compiler, either by inserting

#define NDEBUG

in a header file such as stdhdr.h, or by calling your compiler with the -dNDEBUG option:
cc -dNDEBUG ...

Static Assertions:

static_assert ( bool_constexpr , message )
  • Performs compile-time assertion checking
  • Tests a software assertion at compile time. If the specified constant expression is false, the compiler displays the specified message and the compilation fails with error; otherwise, the declaration has no effect.
  • Static assert is used to make assertions at compile time. When the static assertion fails, the program simply doesn't compile.
  • Run-time assertions in many cases can be used instead of static assertions, but run-time assertions only work at run-time and only when control passes over the assertion.
  • Of course, the expression in static assertion has to be a compile-time constant. It can't be a run-time value.

No comments:

Post a Comment