我的系统使用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); \
}))
这个最后的定义存在哪些问题?
({})
没有什么特殊的地方,除了__extension__
是类似函数的标识符(像宏函数一样,即#define __extension__(...) ...
)需要一个代码块。当表达式为真时,我不确定你的意思 - 返回值是__extension__
返回的任何内容。我不确定assert()
的返回值是否被指定,甚至是否可用。 - Qix - MONICA WAS MISTREATED