C 的 assert宏
等级 5277 次按键
定义自定义的 ASSERT 宏:检查条件并打印带消息的 "Assert passed" 或 "Assert failed",而不是终止程序。x = 10 时前两个检查通过,第三个 x == 5 失败。
C 代码
// cond 为假时打印 "Assert failed",否则打印 "Assert passed",后面跟上 msg// (cond) 加括号是为了保证优先级;do-while(0) 让整个宏表现为一条语句1#define ASSERT(cond, msg) do { \2 if (!(cond)) { \3 printf("Assert failed: %s\n", msg); \4 } else { \5 printf("Assert passed: %s\n", msg); \6 } \7} while(0)8 // 要检查的值9int x = 10;// 10 > 0 为真:打印“Assert passed: x must be positive”10ASSERT(x > 0, "x must be positive");// 10 < 20 为真:打印“Assert passed: x must be less than 20”11ASSERT(x < 20, "x must be less than 20");// 10 == 5 为假:打印“Assert failed: x must equal 5”12ASSERT(x == 5, "x must equal 5");运行结果
Assert passed: x must be positive Assert passed: x must be less than 20 Assert failed: x must equal 5
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 C 代码中需要输入的符号及其出现次数。
"× 10(× 9)× 9\× 8,× 6;× 6{× 3}× 3=× 3:× 2