C++ 多行 DEFINE 指令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6281368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multi-line DEFINE directives?
提问by Adam S
I am not an expert, so go easy on me. Are there any differences between these two code segments?
我不是专家,所以放轻松。这两个代码段之间有什么区别吗?
#define BIT3 (0x1
<
<
3)
static int a;
and
和
#define BIT3 (0x1 << 3) static int a;
Also, is there a way to write the first in one line? What is the point of this multi-line style? Is the following code good?
另外,有没有办法在一行中写第一个?这种多线样式的重点是什么?下面的代码好吗?
#define BIT3 (0x1 << 3)
static int a;
回答by Oliver Charlesworth
A multi-line macro is useful if you have a very complex macro which would be difficult to read if it were all on one line (although it's inadvisable to have very complex macros).
如果您有一个非常复杂的宏,如果它们都在一行上就会难以阅读,那么多行宏很有用(尽管不建议拥有非常复杂的宏)。
In general, you can write a multi-line define using the line-continuation character, \
. So e.g.
通常,您可以使用行继续符\
. 所以例如
#define MY_MACRO printf( \
"I like %d types of cheese\n", \
5 \
)
But you cannot do that with your first example. You cannot split tokens like that; the <<
left-shift operator must always be written without any separating whitespace, otherwise it would be interpreted as two less-than operators. So maybe:
但是你不能用你的第一个例子做到这一点。你不能像那样拆分代币;该<<
左移操作人员必须始终没有任何空格分开写,否则会被解释为两低于运营商。所以也许:
#define BIT3 (0x1 \
<< \
3) \
static int a;
which is now equivalent to your second example.
现在相当于你的第二个例子。
[Although I'm not sure how that macro would ever be useful!]
[虽然我不确定那个宏会有什么用处!]
回答by phoxis
For example:
例如:
#define fact(f,n) for (f=1; (n); (n)--) \
f*=n;
You can separate the lines with the \
character. Note that it is not macro specific. You can add the \
character in your code whenever you would like to break a long line.
您可以将行与\
字符分开。请注意,它不是特定于宏的。您可以随时\
在代码中添加该字符来打断长行。
回答by Prof. Falken contract breached
The first one should not work. Lines should be separated with backslash THEN newline. Like so:
第一个不应该工作。行应该用反斜杠 THEN 换行符分隔。像这样:
#define SOME_MACRO "whatever" \
"more" \
"yet more"