为什么在宏中不允许使用 ifndef?

Why ifndef is not allowed inside a macro?

我想写这样的东西:

#define set(x){cout<< x}
int main() {
    set(#ifdef A  1 #else 3 #endif );
    return 0;
}

但是它不起作用,我的问题是为什么? 为什么 C 不允许代码运行?宏中的 ifndef 有什么问题?

谁说不行?

set(
    #ifdef A
        1 
    #else
        3
    #endif
);

以上代码段按预期工作。 Demo on Godbolt

# 是启动预处理器指令的特殊字符,必须位于行的开头(在可选空格之后),因此您必须分隔成新行。无论如何,人们通常不会这样做,因为他们会这样做

#ifdef A
    set(1);
#else
    set(3);
#endif

#ifdef A
    #define VAL 1
#else
    #define VAL 3
#endif
set(VAL);

请注意 cout << 不是 C 并且您在宏中缺少一个分号。应该是{cout<< x;}