do while(false)模式 [英] do while(false) pattern

查看:157
本文介绍了do while(false)模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:


为什么 do while(false)必须在下面的宏?

  #define LOG(message,...)\ 
do {\
Lock< MutualExclusion> lock(logMutex); \

....很多代码...
} while(false)

我不认为它服务于任何功能的目的。我可以忽略某些东西吗?

它把一个块转换成一个语句。如果你只是使用块(例如 {} 中的代码),可能会发生奇怪的事情,例如

  #define STUFF()\ 
{do_something(); do_something_else(); }

if(cond)
STUFF();
else
// ...

额外的分号句法。 do {} while(false)而是一个单独的语句。



宏观此处。 p>

Possible Duplicate:
Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?

Why is the do while(false) necessary in the macros below?

#define LOG(message, ...) \
do { \
Lock<MutualExclusion> lock (logMutex); \

 .... a lot of code ...
} while (false)

I dont think it serves any functional purpose. Am I overlooking something?

解决方案

It turns a block into a single statement. If you just use a block (i.e. code enclosed in {}) strange things can happen, for example

#define STUFF() \
  { do_something(); do_something_else(); }

if (cond)
    STUFF();
else
    //...

the extra semi-colon breaks the syntax. The do {} while(false) instead is a single statement.

You can find more about this and other macro tricks here.

这篇关于do while(false)模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆