什么是宏&QUOT之间的差异; STR的#define(x)的#X'QUOT;和" STR的#define(x)的VAL(X)"与"#定义VAL(X)#X'QUOT ;? [英] What's the difference between the macros "#define STR(x) #x" and "#define STR(x) VAL(x)" with "#define VAL(x) #x"?

查看:258
本文介绍了什么是宏&QUOT之间的差异; STR的#define(x)的#X'QUOT;和" STR的#define(x)的VAL(X)"与"#定义VAL(X)#X'QUOT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我用这个code:

 的#include<&stdio.h中GT;
STR的#define(X)#XINT主要(无效)
{
    的printf(__ FILE__ STR(__ LINE__)你好\\ N!);
    返回0;
}

它打印

  hello.c__LINE__hello!

但是当我使用这样的:

 的#include<&stdio.h中GT;
STR的#define(x)的VAL(X)
#定义VAL(X)#XINT主要(无效)
{
    的printf(__ FILE__ STR(__ LINE__)你好\\ N!);
    返回0;
}

它打印

  hello.c7hello!

什么

之间的区别

 的#define STR(x)的#X

 的#define STR(x)的VAL(X)
#定义VAL(X)#X


解决方案

参数给宏本身是宏展开,的除了的在宏参数名出现在宏体与stringifier#或令牌贴膜##。

在第一种情况下,STR的说法是的的宏扩展,所以你只得到了LINE宏的名称。

在第二种情况下,STR的参数的的宏扩展时,它代入VAL的定义,所以它的工作原理 - 你得到实际的行号,因为LINE宏扩大。

When I use this code:

#include <stdio.h>
#define STR(x) #x

int main(void)
{
    printf(__FILE__ STR(__LINE__) "hello!\n");
    return 0;
}

it prints

hello.c__LINE__hello!

but when I use this:

#include <stdio.h>
#define STR(x) VAL(x)
#define VAL(x) #x

int main(void)
{
    printf(__FILE__ STR(__LINE__) "hello!\n");
    return 0;
}

it prints

hello.c7hello!

what's the difference between

#define STR(x) #x

and

#define STR(x) VAL(x)
#define VAL(x) #x

解决方案

Arguments to macros are themselves macro-expanded, except where the macro argument name appears in the macro body with the stringifier # or the token-paster ##.

In the first case, the argument of STR is not macro-expanded, and so you just get the name of the LINE macro.

In the second case, the argument of STR is macro-expanded when it is substituted into the definition of VAL, and so it works -- you get the actual line number because the LINE macro is expanded.

这篇关于什么是宏&QUOT之间的差异; STR的#define(x)的#X'QUOT;和&QUOT; STR的#define(x)的VAL(X)&QUOT;与&QUOT;#定义VAL(X)#X'QUOT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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