• 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

  • 相关阅读:
    ExtJS学习之路第一步:对比jQuery,认识ExtJS
    创建Windows服务(C++)
    吴恩达2014机器学习教程笔记目录
    在Hexo中渲染MathJax数学公式
    Linux服务器性能检测命令集锦
    Redis开启AOF导致的删库事件
    从表扩展增加列属性说起
    数据库规约解读
    MySQL规约(阿里巴巴)
    HDFS运行原理
  • 原文地址:https://www.cnblogs.com/zzdbullet/p/10185249.html
Copyright © 2020-2023  润新知