Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki Markup
C99, Section 7.2.1.1, defines {{assert()}} to have the following behavior \[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\]:

The assert macro puts diagnostic tests into programs; it expands to a void expression. When it is executed, if expression (which shall have a scalar type) is false (that is, compares equal to 0), the assert macro writes information about the particular call that failed (including the text of the argument, the name of the source file, the source line number, and the name of the enclosing function---the function—the latter are respectively the values of the preprocessing macros __FILE__ and __LINE__ and of the identifier __func__) on the standard error stream in an implementation-defined format. It then calls the abort function.

...

See ERR04-C. Choose an appropriate termination strategy, for more information on program termination strategies and MSC11-C. Incorporate diagnostic tests using assertions, for more information on using the assert() macro.

Noncompliant Code Example

The following This noncompliant code defined example defines a function intended to be that is called before the program exits , to properly clean up after itself.

Code Block
bgColor#ffcccc
void cleanup(void) {
  /* delete temporary files, restore consistent state, etc. */
}

int main(void) {
  if (atexit(cleanup) != 0) {
    /* Handle Errorerror */
  }

  /* ... */

  assert(/* something bad didn't happen */);

  /* ... */
}

...

In this compliant solution, the call to assert() is replaced with an if statement that calls exit() to ensure that the proper termination routines are run.

Code Block
bgColor#ccccff
void cleanup(void) {
  /* delete temporary files, restore consistent state, etc */
}

int main(void) {
  if (atexit(cleanup) != 0) {
    /* Handle Errorerror */
  }

  /* ... */

  if (/* something bad happened */) {
    exit(EXIT_FAILURE);
  }

  /* ... */
}

...