Sonntag, 22. Februar 2015

Quick C Tricks - Assertions With Error Message

This quick post is the last little trick I got out of the book Patterns in C written by Adam Tornhill. The technique presents comments for assertions which also appear as an error message if failing.

Here is an example:
#include <assert.h>

int main() {
   assert(1 == 2 && "This is an error message");

Running the code gives the following result:

main: Assertion `1 == 2 && "This is an error message"' failed.

This trick works since the string This is an error message itself evaluates to True. The actual checking is taking place in the first part of the assertion, a second appended True does not influence this behavior.

You can argue that this is a hack (that's true) but giving the user some guidance in the event of failure is also not a bad idea.;

Keine Kommentare:

Kommentar veröffentlichen