#ifdef具有多个令牌,这合法吗? [英] #ifdef with multiple tokens, is this legal?

查看:101
本文介绍了#ifdef具有多个令牌,这合法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我遇到了一些C#代码,其中包含这样的#ifdef子句:

Today I came across some C++ code that contains an #ifdef clause like this:

#ifdef DISABLE_UNTIL OTHER_CODE_IS_READY
   foo();
#endif

请注意"DISABLE_UNTIL"和"OTHER_CODE_IS_READY"之间的空格.基本上,在#ifdef行中指定了两个令牌.

Note the space between "DISABLE_UNTIL" and "OTHER_CODE_IS_READY". Essentially there are two tokens specified in the #ifdef line.

我的问题是,这是合法的C ++代码吗? (g ++编译时没有任何错误,并且显然只是忽略了第二个标记).而且如果合法,第二个令牌应该有效吗?

My question is, is this legal C++ code? (g++ compiles it without any errors, and it apparently just ignores the second token). And if it is legal, should the second token have any effect?

推荐答案

[C++11 16.1][C++11 16.5][C99 6.10.1/4]都说这是无效的.

[C++11 16.1], [C++11 16.5] and, incidentally, [C99 6.10.1/4] all say that this is invalid.

if-group :
# if 常量表达式 换行符 group opt
# ifdef 标识符 换行符 group opt
# ifndef 标识符 换行符 group opt

if-group:
# if constant-expression new-line groupopt
# ifdef identifier new-line groupopt
# ifndef identifier new-line groupopt

只有一个标识符是合法的.

Only one identifier is legal.

GCC自己的文档同意.

我自己的测试建议仅接受第一个标识符,而第二个则被丢弃;这可能是为了简化实施,但是该标准确实需要在此处进行诊断,因此,当至少使用-pedantic标志时,应该看到此信息.

My own tests suggest that only the first identifer is accepted, and the second is simply discarded; this may be to ease the implementation, but the standard does require a diagnostic here, so you should see this when you use the -pedantic flag at least.

#include <iostream>
using namespace std;

#define A
#define B

int main() {
    #ifdef A
    std::cout << "a ";
    #endif

    #ifdef B
    std::cout << "b ";
    #endif

    #ifdef C
    std::cout << "c ";
    #endif

    #ifdef B C
    std::cout << "bc ";
    #endif

    #ifdef C B
    std::cout << "cb ";
    #endif

    return 0;
}

// Output: "a b bc"
// Note: "cb" *not* output


Coliru安装的GCC发出它使用或或没有-pedantic .


Coliru's installation of GCC emits it with or without -pedantic.

这篇关于#ifdef具有多个令牌,这合法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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