哪种类型的内容可以用作C预处理程序宏的参数? [英] What type of content is allowed to be used as arguments for C preprocessor macro?
问题描述
老实说,我非常了解C编程语言的语法,但是对C预处理器的语法几乎一无所知,尽管有时我会在编程实践中使用它。
Honestly I know the syntax of the C programming language well, but know almost nothing about the syntax of the C preprocessor, although I use it in my programming practice sometimes.
这个问题。假设我们有一个扩展为空的简单宏:
So the question. Suppose we have a simple macro that expands to nothing:
#define macro(param)
可以在宏调用构造中使用的语法有什么限制?
What is the restrictions for the syntax that can be put inside macro invoking construction?
调用宏时,绝对不可能使用单个或多个逗号:
It is certainly impossible to use single or multiple comma when invoking the macro:
macro(,); // won't compile
但是,如果我们将逗号放在方括号中,它将被C接受预处理器:
However if we put the comma into the brackets it will be accepted by C preprocessor:
macro((,)); // compiles fine
当然,您不能使用注释字符:
Of course, you can't use the comment characters:
macro(//); // compile error
据我所知,注释是由预处理程序本身处理的。
because, as far as I know, comments are processed by preprocessor itself.
使用宏时,也不允许使用不引号和圆括号:
Unclosed quotes and round brackets aren't allowed too when using the macro:
macro("); // compile error
但是可以很好地接受C语法中未使用的字符:
But characters unused in the C syntax are accepted well:
macro(@#$); // compiles
即使外语字符也可以正常工作:
Even characters of foreign languages work fine:
macro(бла-бла-бла я пишу по-русски); // compiles too
我可以使用随机有效的C吗/ C ++代码在调用宏时用大括号括起来吗?我可以使用不带大括号的随机有效C / C ++代码吗?以下代码似乎可以很好地编译:
Can I use a random valid C/C++ code in curly brackets when invoking the macro? Can I use a random valid C/C++ code without curly brackets? The following code seems to compile fine:
macro(int a = 5; printf("%d\n", a););
推荐答案
您不能通过提议的方案传递要忽略的任意文本:
You cannot pass arbitrary text to be ignored with your proposed scheme:
-
C预处理程序将读取输入文件,并在剥离注释后将其解析为一系列预处理标记,以将其作为参数传递给宏。它与括号匹配,以确定哪些标记构成由
,
分隔的参数。
包含带有无法识别的转义序列或单独的反斜杠的字符串或字符常量的文本不会解析为标准预处理令牌。 macro(@#$);
是否编译取决于实现。
Text containing strings or character constants with unrecognized escape sequences or stand alone backslashes does not parse as standard preprocessing token. Whether macro(@#$);
compiles is implementation dependent.
请注意,您可以使用通过将宏定义为采用可变数量的参数来解决 问题:
Note however that you can work around the ,
problem by defining your macro as taking a variable number of arguments:
#define macro(...)
这篇关于哪种类型的内容可以用作C预处理程序宏的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!