开发者

What Kind Of Macro Is this?

I came across this following code:

#include<stdio.h>
#define d(x) x(#x[3])
int main(){
d(put开发者_如何学Cchar);
}

Which prints c as the output. I wonder what does the macro #define d(x) x(#x[3]) does? In C language is there an operator like #? I can see this inside the macro body i.e here x(#x[3]). According to my normal eye it looks something different I see in C language but actually What does this does?

Edit : Whats the real use of # in real world?

I'm a novice in C and it will be good if the explanation is in simple terms. Thanks in advance.


The character '#' is a stringizer -- it turns a symbol into a string. The code becomes

putchar("putchar"[3]);


The hash sign means "stringify", so d(x) expands to putchar("putchar"[3]), whence the c.


From here:

Function macro definitions accept two special operators (# and ##) in the replacement sequence: If the operator # is used before a parameter is used in the replacement sequence, that parameter is replaced by a string literal (as if it were enclosed between double quotes)

#define str(x) #x
cout << str(test);

Put simply, it changes the "x" parameter into a string. In this case test becomes a char array containing 't', 'e', 's', 't', '\0'.


The # is a pre-processor operator which turns a literal into a string. In fact your d macro prints the fourth char of the converted string of your literal.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜