assert() with message assert() with message c c

assert() with message


Use -Wno-unused-value to stop the warning; (the option -Wall includes -Wunused-value).

I think even better is to use another method, like

assert(condition && "message");


Try:

#define assert__(x) for ( ; !(x) ; assert(x) )

use as such:

assert__(x) {    printf("assertion will fail\n"); }

Will execute the block only when assert fails.

IMPORTANT NOTE: This method will evaluate expression x twice, in case x evaluates to false! (First time, when the for loop is checking its condition; second time, when the assert is evaluating the passed expression!)


If you want to pass a formatted message, you could use the following macros:

#include <stdio.h>#include <errno.h>#include <string.h>#include <assert.h>#define clean_errno() (errno == 0 ? "None" : strerror(errno))#define log_error(M, ...) fprintf(stderr, "[ERROR] (%s:%d: errno: %s) " M "\n", __FILE__, __LINE__, clean_errno(), ##__VA_ARGS__)#define assertf(A, M, ...) if(!(A)) {log_error(M, ##__VA_ARGS__); assert(A); }

Then use it like printf:

// With no argsassertf(self != NULL,"[Server] Failed to create server.");// With formatting argsassertf((self->socket = u_open(self->port)) != -1,"[Server] Failed to bind to port %i:",self->port);// etc...

Output:

[ERROR] (../src/webserver.c:180: errno: Address already in use) [Server] Failed to bind to port 8080: webserver: ../src/webserver.c:180: server_run: Assertion `(self->socket = u_open(self->port)) != -1' failed.

Based on http://c.learncodethehardway.org/book/ex20.html