static_assert和assert

assert运行时断言

#include<cassert>
#include<cstring>
#include<iostream>
using namespace std;

//使用NDEBUG来禁用assert宏
#define NDEBUG
//禁用后程序将继续执行,不会提示错误或崩溃
#ifdef NDEBUG
#define assert(expr) (static_cast<void> (0))
#else

#endif

char* ArrayAlloc(int n){
    //运行时进行断言
    assert(n>2);
    return new char[n];
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    char* tempa = ArrayAlloc(1);
    return a.exec();
}

static_assert静态断言

#include<cassert>
#include<cstring>
#include<iostream>
using namespace std;

//c11之前可以实现的静态断言方式,通过除0
#define asset_static(e)\
    do{\
    enum{asset_static__=1/(e)};\
    }while(0)

template<typename T,typename U>int bit_copy(T& t1,U& u1){
    //静态断言-c11,表达式的结果为常量,写在函数体外是较好的选择
    //如果程序需要进行运行时检测,还是使用assert宏
    static_assert(sizeof(u1) == sizeof(t1),"t1 and u1 must have same width.");
    memcpy(&t1,&u1,sizeof(u1));
}
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    int tempa1 = 0x2468;
    double b;
    bit_copy(tempa1,b);

    return a.exec();
}

enum FeatureSupports{
    C99=0x0001,
    ExtInt=0x0002,
    SAssert=0x0004,
    NoExcept=0x0008,
    SMAX=0x0010,
};
struct Compiler{
    const char* name;
    int spp;//使用FeatureSupports枚举
};

    //检查枚举值是否完备
    assert((SMAX-1)==(C99|ExtInt|SAssert|NoExcept));
    Compiler tempa={"c1",(C99|SAssert)};
    if(tempa.spp&C99){
        qDebug() << "spp&C99";
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力减肥的小胖子5

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值