多行 DEFINE 指令?

发布于 2024-11-14 06:07:16 字数 305 浏览 1 评论 0原文

我不是专家,所以对我宽容一些。这两个代码段之间有什么区别吗?

#define BIT3 (0x1
<
<
3)
static int a;

另外

#define BIT3 (0x1 << 3) static int a;

,有没有办法将第一行写成一行?这种多线样式有什么意义呢?下面的代码好不好?

#define BIT3 (0x1 << 3)
static int a;

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;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

七色彩虹 2024-11-21 06:07:16

如果您有一个非常复杂的宏,如果它全部在一行上,则很难阅读(尽管不建议使用非常复杂的宏),那么多行宏很有用。

通常,您可以使用续行符 \ 编写多行定义。所以例如

#define MY_MACRO    printf( \
    "I like %d types of cheese\n", \
    5 \
    )

但是你不能用你的第一个例子来做到这一点。你不能像这样分割代币; << 左移运算符的编写必须始终没有任何分隔空格,否则它将被解释为两个小于运算符。所以也许:

#define BIT3 (0x1 \
    << \
    3) \
    static int a;

这现在相当于你的第二个例子。

[虽然我不确定这个宏会有什么用处!]

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!]

你又不是我 2024-11-21 06:07:16

例如:

#define fact(f,n)   for (f=1; (n); (n)--) \
                      f*=n;

您可以使用 \ 字符分隔行。请注意,它不是特定于宏的。每当您想要换行长行时,都可以在代码中添加 \ 字符。

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.

爱已欠费 2024-11-21 06:07:16

第一个应该不起作用。行应该用反斜杠然后换行符分隔。就像这样:

#define SOME_MACRO "whatever" \
"more" \
"yet more"

The first one should not work. Lines should be separated with backslash THEN newline. Like so:

#define SOME_MACRO "whatever" \
"more" \
"yet more"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文