do...while(0)

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

贴上一段代码:

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.csdn.net/majianfei1023/article/details/45246865

https://blog.csdn.net/hzhsan/article/details/15815295

猜你喜欢

转载自www.cnblogs.com/zzdbullet/p/10185249.html