C 断言使用

C 断言使用

断言为什么会打断程序执行?因为 __noreturn__

assert.h

# define assert(__e) ((__e) ? (void)0 : __assert_func (__FILE__, __LINE__, \
						       __ASSERT_FUNC, #__e))

void __assert_func (const char *, int, const char *, const char *)
	    _ATTRIBUTE ((__noreturn__));

静态断言 _Static_assert

静态断言将在编译时期被检查

static-assert-in-c

_Static_assert(sizeof(long)==7, this_should_be_true) 


build fail

sas.c:4: error: size of array ‘static_assertion_this_should_be_true’ is negative
#define _Static_assert(COND,MSG) typedef char static_assertion_##MSG[(COND)?1:-1]

关闭断言

开启宏:

CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT

断言关闭风险

assert(func())

以上代码在关闭断言时,会导致 func 不被执行