Assert Error Messages

suggest change

A 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 this works is that a string literal decays to a non-null pointer, which is true in a Boolean context. Adding && 1 to a Boolean expression has no effect on its value. Adding && "error message" likewise does not change the result, but the diagnostic includes the entire expression that failed.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents