【发布时间】:2019-05-26 13:52:02
【问题描述】:
我的系统使用 libc6 2.29。在/usr/include/assert.h可以找到assert()宏的定义:
/* The first occurrence of EXPR is not evaluated due to the sizeof,
but will trigger any pedantic warnings masked by the __extension__
for the second occurrence. The ternary operator is required to
support function pointers and bit fields in this context, and to
suppress the evaluation of variable length arrays. */
# define assert(expr) \
((void) sizeof ((expr) ? 1 : 0), __extension__ ({ \
if (expr) \
; /* empty */ \
else \
__assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION); \
}))
我想知道为什么要使用逗号运算符,以及“The first occurrence of EXPR is not evaluated due to the sizeof”是什么意思。
使用以下定义会有什么问题:
# define assert(expr) \
({ \
if (expr) \
; /* empty */ \
else \
__assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION); \
})
编辑:
如果expr 为真,运算符 ({ }) 会得到什么值?
是否可以将assert()的定义改写如下?
# define assert(expr) \
((void) sizeof ((expr) ? 1 : 0), __extension__ ({ \
if (!expr) \
__assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION); \
}))
最后一个定义的问题在哪里?
【问题讨论】: