C++中do...while(0)的妙用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/89737676

一 点睛

do{...}while(condition)可以表示循环,但你有没有遇到在一些地方宏定义中可以不用循环的地方,也用到了do{...}while(condition),比如有这样的宏:

#define Foo(x) do{\
    printf("first statement\n");\
    printf("second statement\n");\
}while(0) 

粗看会觉得很奇怪,既然循环里面执行了一次,那这个看似多余的do...while(0)有什么意义呢?再看下面这个宏

#define Foo(x) {\
    printf("first statement\n");\
    printf("second statement\n");\
}

这两个看似一样的宏,其实是不一样的。前者定义的宏是一个非复合的语句,而后面却是一个复合语句。假设有下面这个使用场景:

if(true)
    Foo(x);
else
{}

因为宏在预处理的时候会直接展开,采用第2种写法,会变成下面这样:

if(true)
    printf("first statement\n");
    printf("second statement\n");
else
{}

这样会导致else语句孤立而出错。加了do{...}while(condition),就使得宏展开后,仍然保留初始的语义,从而保证程序的正常性。

二 实战

1 正确使用方法

1.1 代码

#include<iostream>
#include<stdio.h>
using namespace std;
#define _DEBUG_
#define Foo(x) do{\
    printf("first statement\n");\
    printf("second statement\n");\
}while(0)
int main(){
    int x=10;
    #ifdef _DEBUG_
       cout<<"File:"<< __FILE__<<",Line:"<< __LINE__<<",x:"<<x<<endl;
       if(true)
           Foo(x);
       else
       {}
    #else
       printf("x = %d\n", x);
       cout<<x<<endl;
   #endif
    return 0;
}

1.2 运行

[root@localhost charpter01]# g++ test.cpp -o test
[root@localhost charpter01]# ./test
File:test.cpp,Line:12,x:10
first statement
second statement

2 错误使用方法

2.1 代码

#include<iostream>
#include<stdio.h>
using namespace std;
#define _DEBUG_
#define Foo(x) {\
    printf("first statement\n");\
    printf("second statement\n");\
}
int main(){
    int x=10;
    #ifdef _DEBUG_
       cout<<"File:"<< __FILE__<<",Line:"<< __LINE__<<",x:"<<x<<endl;
       if(true)
           Foo(x);
       else
       {}
    #else
       printf("x = %d\n", x);
       cout<<x<<endl;
   #endif
    return 0;
}

2.2 运行

[root@localhost charpter01]# g++ test.cpp -o test
test.cpp: In function ‘int main()’:
test.cpp:15:8: error: ‘else’ without a previous ‘if’
        else

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/89737676