// assert() example by gbmhunter for www.mbedded.ninja
// Designed as an example of assert() for embedded systems.
// See http://w...content-available-to-author-only...d.ninja/programming/languages/c/assertions-assert
#include <stdio.h>
#include <stdbool.h>
// Comment out to disable asserts
#define DEBUG
// We will use captial letters for ASSERT to differentiate it from the system-provided
// assert() if it exists.
#ifdef DEBUG
#define ASSERT(exp) ((void)(exp), (exp ? : AssertFailed(__FILE__, __LINE__, #exp)))
#else
#define ASSERT(exp) (void)(0);
#endif
//! @brief Assert failed handling function.
//! @details This will be called by the ASSERT() macro.
void AssertFailed(const char * filename, int lineNumber, const char * expression) {
printf("%s, line %i: Assertion \"%s\" failed.\r\n", filename
, lineNumber
, expression
); }
int main(void) {
// Some really basic (and useless) assert() tests
ASSERT(true);
ASSERT(false);
// Some more practical assert tests
int x = 3;
((void)(x = 7), x==7 ? x = 4: x = 2);
ASSERT(x == 3);
ASSERT(x == 4);
// An assert() with an embedded assignment should
// give a compiler error.
//ASSERT(x = 1);
return 0;
}
Ly8gYXNzZXJ0KCkgZXhhbXBsZSBieSBnYm1odW50ZXIgZm9yIHd3dy5tYmVkZGVkLm5pbmphCi8vIERlc2lnbmVkIGFzIGFuIGV4YW1wbGUgb2YgYXNzZXJ0KCkgZm9yIGVtYmVkZGVkIHN5c3RlbXMuCi8vIFNlZSBodHRwOi8vdy4uLmNvbnRlbnQtYXZhaWxhYmxlLXRvLWF1dGhvci1vbmx5Li4uZC5uaW5qYS9wcm9ncmFtbWluZy9sYW5ndWFnZXMvYy9hc3NlcnRpb25zLWFzc2VydAoKI2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRib29sLmg+CgovLyBDb21tZW50IG91dCB0byBkaXNhYmxlIGFzc2VydHMKI2RlZmluZSBERUJVRwoKLy8gV2Ugd2lsbCB1c2UgY2FwdGlhbCBsZXR0ZXJzIGZvciBBU1NFUlQgdG8gZGlmZmVyZW50aWF0ZSBpdCBmcm9tIHRoZSBzeXN0ZW0tcHJvdmlkZWQKLy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’:
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);
^~~~~~