Skip to content

Instantly share code, notes, and snippets.

@bergkvist
Last active September 5, 2022 23:18
Show Gist options
  • Save bergkvist/c0157d140ca00f75477dcf97d5638133 to your computer and use it in GitHub Desktop.
Save bergkvist/c0157d140ca00f75477dcf97d5638133 to your computer and use it in GitHub Desktop.
Useful assertion macros in C which include debug information like file, line number and error message.
// These require compiler support for statement expressions (https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html)
#define assert_ok(e) ({int x = (e); if (x < 0) { printf("%s:%d: ", __FILE__, __LINE__); fflush(stdout); perror(#e); abort(); } x;})
#define assert_ptr(e) ({void* p = (e); if (p == NULL) { printf("%s:%d: %s: NULL pointer returned\n", __FILE__, __LINE__, #e); abort(); } p;})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment