zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Sass
    将100以内同时能被3和5整除的数输出
    Html小插件
    微信小程序一些demo链接地址
    .net MVC4一个登陆界面加验证
    Zeu.js
    Google 开发的、最好用、功能最强大的网页测速与网站性能分析工具
    .net基本面试题
    C#简单的九九乘法表
    请编程实现一个冒泡排序算法
  • 原文地址:https://www.cnblogs.com/zzdbullet/p/10185249.html
Copyright © 2011-2022 走看看