fork download
  1. // assert() example by gbmhunter for www.mbedded.ninja
  2. // Designed as an example of assert() for embedded systems.
  3. // See http://w...content-available-to-author-only...d.ninja/programming/languages/c/assertions-assert
  4.  
  5. #include <stdio.h>
  6. #include <stdbool.h>
  7.  
  8. // Comment out to disable asserts
  9. #define DEBUG
  10.  
  11. // We will use captial letters for ASSERT to differentiate it from the system-provided
  12. // assert() if it exists.
  13. #ifdef DEBUG
  14. #define ASSERT(exp) ((void)(exp), (exp ? : AssertFailed(__FILE__, __LINE__, #exp)))
  15. #else
  16. #define ASSERT(exp) (void)(0);
  17. #endif
  18.  
  19. //! @brief Assert failed handling function.
  20. //! @details This will be called by the ASSERT() macro.
  21. void AssertFailed(const char * filename, int lineNumber, const char * expression) {
  22. printf("%s, line %i: Assertion \"%s\" failed.\r\n", filename, lineNumber, expression);
  23. }
  24.  
  25. int main(void) {
  26.  
  27. // Some really basic (and useless) assert() tests
  28. ASSERT(true);
  29. ASSERT(false);
  30.  
  31. // Some more practical assert tests
  32. int x = 3;
  33.  
  34. ((void)(x = 7), x==7 ? x = 4: x = 2);
  35. ASSERT(x == 3);
  36. ASSERT(x == 4);
  37.  
  38. // An assert() with an embedded assignment should
  39. // give a compiler error.
  40. //ASSERT(x = 1);
  41.  
  42. return 0;
  43. }
Compilation error #stdin compilation error #stdout 0s 9432KB
stdin
Standard input is empty
compilation info
prog.c: In function ‘main’:
prog.c:34:37: error: lvalue required as left operand of assignment
     ((void)(x = 7), x==7 ? x = 4: x = 2);
                                     ^
prog.c:14:44: warning: the omitted middle operand in ?: will always be ‘true’, suggest explicit middle operand [-Wparentheses]
  #define ASSERT(exp)  ((void)(exp), (exp ? : AssertFailed(__FILE__, __LINE__, #exp)))
                                            ^
prog.c:35:2: note: in expansion of macro ‘ASSERT’
  ASSERT(x == 3);
  ^~~~~~
prog.c:14:44: warning: the omitted middle operand in ?: will always be ‘true’, suggest explicit middle operand [-Wparentheses]
  #define ASSERT(exp)  ((void)(exp), (exp ? : AssertFailed(__FILE__, __LINE__, #exp)))
                                            ^
prog.c:36:2: note: in expansion of macro ‘ASSERT’
  ASSERT(x == 4);
  ^~~~~~
stdout
Standard output is empty