本文介绍了do { ... } while (0) — 它有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
为什么有时C/C++ 宏中没有意义的 do/while 和 if/else 语句?

我已经看到这种表达方式 10 多年了.我一直在想它有什么好处.由于我主要在 #defines 中看到它,我认为它适用于内部作用域变量声明和使用中断(而不是 goto).

I've been seeing that expression for over 10 years now. I've been trying to think what it's good for. Since I see it mostly in #defines, I assume it's good for inner scope variable declaration and for using breaks (instead of gotos.)

它对其他东西有好处吗?你会用吗?

Is it good for anything else? Do you use it?

推荐答案

它是 C 中唯一可以用来#define 多语句操作的构造,在后面放一个分号,并且仍然在里面使用if 语句.一个例子可能会有所帮助:

It's the only construct in C that you can use to #define a multistatement operation, put a semicolon after, and still use within an if statement. An example might help:

#define FOO(x) foo(x); bar(x)

if (condition)
    FOO(x);
else // syntax error here
    ...;

即使使用大括号也无济于事:

Even using braces doesn't help:

#define FOO(x) { foo(x); bar(x); }

if 语句中使用它需要你省略分号,这是违反直觉的:

Using this in an if statement would require that you omit the semicolon, which is counterintuitive:

if (condition)
    FOO(x)
else
    ...

如果你这样定义 FOO:

If you define FOO like this:

#define FOO(x) do { foo(x); bar(x); } while (0)

那么以下在语法上是正确的:

then the following is syntactically correct:

if (condition)
    FOO(x);
else
    ....

这篇关于do { ... } while (0) — 它有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 17:33