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

一 点睛

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

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值