Assert Error Messages
suggest changeA trick exists that can display an error message along with an assertion. Normally, you would write code like this
void f(void *p) { assert(p != NULL); /* more code */ }
If the assertion failed, an error message would resemble
Assertion failed: p != NULL, file main.c, line 5
However, you can use logical AND (&&
) to give an error message as well
void f(void *p) { assert(p != NULL && "function f: p cannot be NULL"); /* more code */ }
Now, if the assertion fails, an error message will read something like this
Assertion failed: p != NULL && “function f: p cannot be NULL”, file main.c, line 5
The reason as to why this works is that a string literal always evaluates to non-zero (true). Adding && 1
to a Boolean expression has no effect. Thus, adding && "error message"
has no effect either, except that the compiler will display the entire expression that failed.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents