在 cocos2d-x 源码 中,有大量的这种 do{}while(0)
的用法,例如这个:
do
{
CCImage* pImage = new CCImage();
CC_BREAK_IF(NULL == pImage);
bRet = pImage->initWithString(text, (int)dimensions.width, (int)dimensions.height, eAlign, fontName, (int)fontSize);
CC_BREAK_IF(!bRet);
bRet = initWithImage(pImage);
CC_SAFE_RELEASE(pImage);
} while (0);
根据语意,这样写至少保证do后面的代码块执行一次。
这样写的意义是什么?为什么不直接使用块,而一定要加上 do while 循环?
I found this question and searched a lot. Is the person who asked the question not from SF? Haha, just kidding
{}
.do while
loop, you can usebreak
to achieve this purpose.goto
, some companies do not allow the use ofgoto
.兼容
various compilers.宏
there will be no errors when unfolding. If you put it directly in花括号
, it will be wrongThis article is very detailed
Do while(0) is also useful in macro definition #define
Code without braces
Code with braces
Code of do while(0)
Block-level scope. Avoid variable names inside {} blocks from spreading into the upper scope. The advantage is that it reduces the number of names that need to be remembered in the outer scope and reduces the possibility of misuse of these variables.
Specifically, in this code,
pImage
is restricted to be used only in this block, and cannot be used outside this block to avoid misuse by programmers and avoid name conflicts.Common in languages that support block-level scoping, such as C++/Java. gcc also supports writing only curly braces:
Another function is to use goto to unify error handling, such as:
If you use do{}while(0), it will look like this
Do-while is commonly used in macros, such as
Call this macro in code:
Using do-while, the above macro call can look like a "function call", and there can be a semicolon at the end of the sentence
Because
do{} while(0);
can have a semicolon at the end and use braces to enclose the statement;Without do-while, the above macro is written as:
When calling, most people will use it like this: