包含 comptime 断言的整数常量表达式宏

Integer constant expression macros with comptime assertions in them

本文关键字:常量 表达式 整数 comptime 断言 包含      更新时间:2023-10-16

我的一些C宏,需要扩展到整数常量表达式,基于以下内容进行编译时断言:

#define stc_assert_expr(CexprB) sizeof(struct{int _:(CexprB)?1:-1;})

也可以拼写为

#include <assert.h>
#define stc_assert_expr(CexprB) sizeof(struct{static_assert(CexprB,#CexprB);})
//^not sure if this is legal C but it compiles with gcc and clang
//(I'm using the bitfield version anyway, which is definitely legal C)

愚蠢的示例用法:

#include <assert.h>
#define stc_assert_expr(CexprB) sizeof(struct{int _:(CexprB)?1:-1;})
int main(int argc, char**argv)
{
#define minus1(X) (0*stc_assert_expr((X)>0)+(X)-1) 
    /*an integer constant expression with an assertionin it*/
    char ar[minus1(3)];
    switch(argc){
        case minus1(2): ;
    }
}

假设我想使这些宏也可以在C++中使用。

上面的例子不起作用,因为C++不接受 sizeof 中的结构定义。是否有一种C++结构可以替换我的stc_assert_expr(CexprB)来保持static_assert语义?

您可以使用数组表达式而不是结构定义 - 负数组大小在两种语言中都是非法的:

#define stc_assert_expr(condition) sizeof(char[(condition) ? 1 : -1])