do...while(0)

本文探讨了宏定义在C/C++中实现局部作用域的方法,通过do...while(0)增强宏的安全性,避免了代码块被意外分割。同时,讨论了goto语句在错误处理中的应用及替代方案,使用break语句简化代码结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、宏定义,实现局部作用域

贴上一段代码:

void print()
{
    cout<<"print: "<<endl;
}
 
void send()
{
    cout <<"send: "<<endl;
}
 
#define LOG print();send();
 
int main(){
    
    if (false)
        LOG
 
    cout <<"hello world"<<endl;
 
    system("pause");
    return 0;
}

显然,代码输出

send:
hello world

因为define只有替换的作用,所以预处理后,代码实际是这样的:

    if (false)
        print();
    send();
 
    cout <<"hello world"<<endl;

在宏中加入do...while(0):

#define LOG do{print();send();}while (0);
 
int main(){
    
    if (false)
        LOG
    else
    {
        cout <<"hello"<<endl;
    }
 
 
    cout <<"hello world"<<endl;
 
    system("pause");
    return 0;
}

相当于:

    if (false)
        do{
            print();
            send();
        }while (0);
    else
    {
        cout <<"hello"<<endl;
    }
 
 
    cout <<"hello world"<<endl;

 

二、替代goto

int dosomething()
{
    return 0;
}
 
int clear()
{
 
}
 
int foo()
{
    int error = dosomething();
 
    if(error = 1)
    {
        goto END;
    }
 
    if(error = 2)
    {
        goto END;
    }
 
END:
    clear();
    return 0;
}

goto可以解决多个if的时候,涉及到内存释放时忘记释放的问题,但是多个goto,会显得代码冗余,并且不符合软件工程的结构化,不建议用goto,可以改成如下:

int foo()
{
    do 
    {
        int error = dosomething();
 
        if(error = 1)
        {
            break;
        }
 
        if(error = 2)
        {
            break;
        }
    } while (0);
    
    clear();
    return 0;
}

参考:

https://blog.youkuaiyun.com/majianfei1023/article/details/45246865

https://blog.youkuaiyun.com/hzhsan/article/details/15815295

转载于:https://www.cnblogs.com/zzdbullet/p/10185249.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值