Page 56 - C-Language
P. 56

Chapter 5: Assertion




        Introduction



        An assertion is a predicate that the presented condition must be true at the moment the assertion
        is encountered by the software. Most common are simple assertions, which are validated at
        execution time. However, static assertions are checked at compile time.


        Syntax



            •  assert(expression)
            •  static_assert(expression, message)
            •  _Static_assert(expression, message)


        Parameters



          Parameter     Details


          expression    expression of scalar type.

          message       string literal to be included in the diagnostic message.



        Remarks



        Both assert and static_assert are macros defined in assert.h.

        The definition of assert depends on the macro NDEBUG which is not defined by the standard library.
        If NDEBUG is defined, assert is a no-op:


         #ifdef NDEBUG
         #  define assert(condition) ((void) 0)
         #else
         #  define assert(condition) /* implementation defined */
         #endif


        Opinion varies about whether NDEBUG should always be used for production compilations.


            •  The pro-camp argues that assert calls abort and assertion messages are not helpful for end
              users, so the result is not helpful to user. If you have fatal conditions to check in production
              code you should use ordinary if/else conditions and exit or quick_exit to end the program.
              In contrast to abort, these allow the program to do some cleanup (via functions registered
              with atexit or at_quick_exit).
            •  The con-camp argues that assert calls should never fire in production code, but if they do,
              the condition that is checked means there is something dramatically wrong and the program




        https://riptutorial.com/                                                                               32
   51   52   53   54   55   56   57   58   59   60   61