简体   繁体   English

从C语言的printf语句中调用宏函数

[英]Macro function call from within printf statement in C

I am facing a problem with understanding the use of macro function calls from within a printf() statement. 我在使用printf()语句中理解宏函数调用的使用时遇到了问题。

I have the code below : 我有以下代码:

#include<stdio.h>
#define f(g,h) g##h
main()
{
    printf("%d",f(100,10));
}

This code outputs "10010" as the answer. 此代码输出“10010”作为答案。

I have learned that macro function call simply copy pastes the macro function code in place of the call with the arguments replaced. 我已经知道宏函数调用只是复制粘贴宏函数代码代替调用替换参数。

So the code should be like : 所以代码应该是这样的:

#include<stdio.h>
#define f(g,h) g##h
main()
{
    printf("%d",100##10);
}

But when i executed the above code separately with substituted macro,i get a compilation error. 但是当我用替换宏分别执行上面的代码时,我得到一个编译错误。

So how does the first code gives 10010 as the answer while the second code gives a compilation error? 那么第一个代码如何给出10010作为答案而第二个代码给出了编译错误呢?

The preprocessor concatenation operator ## is done before the macro is replaced. 预处理器连接运算符## 替换宏之前完成。 It can only be used in macro bodies. 它只能在宏体中使用。

Operator ## has speacial meaning for preprocessor, it's a token-paste operator which 'glues' two tokens together. 运算符##具有预处理器的特殊含义,它是一个标记粘贴运算符,它将两个标记“粘合”在一起。 So in your case, g and h are 'glued' together, resulting in new token - int literal 10010 . 所以在你的情况下, gh被“粘合”在一起,产生新的令牌 - int literal 10010

在宏中有一些像##这样的特殊字符会改变规则“只是替换文本”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM