C语言变量名转字符串的方法

C语言中将变量名转换成字符串使用的是#符号,来看下边两个宏定义:

#define name2str(name) (#name)
#define print_val(x) printf(#x" = %d\n", x)

使用的时候自动将相应的变量名转换成字符串,示例代码:

int main()
{
    int a = 10;
    short b = 11;
    char c = 12;
    void *addr = (void *)123456;
    int xyz = 100;
 
    printf("welcome to visit http://blog.csdn.net/veabol\n");
    printf("%s = %d\n", name2str(xyz), xyz);
    print_val(a);
    print_val(b);
    print_val(c);
    print_val(d);
 
    return 0;
}

输出内容:

Welcome to visit http://blog.csdn.net/veabol
xyz = 100
a = 10
b = 11
c = 12
addr = 123456

 

原文链接:

https://blog.csdn.net/Veabol/article/details/76491792

 
posted @ 2018-11-08 11:22  小时候挺菜  阅读(2802)  评论(0编辑  收藏  举报