C++ 中 # 和 ## 的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/davied9/article/details/81902166

# 和 ## 在宏定义(define)中经常可以看到,是预编译过程中的常用语句,本文记录了本人探索 # 和 ## 区别以及使用的内容

先简单的将这两个符号进行标签化,然后再记录具体实验。

#   -- 转换, 完成代码到字符串的转换

## -- 连接, 完成代码的连接

示例:

1. # 转换代码为字符串

#define CONVERT(name) #name

int main(int argc, char* argv[])
{
    printf("You and %s are friends.\n", CONVERT(James));
    return 0;
}

    这里, James 将在预编译过程中被转换为字符串 "James" 。

2. ## 代码连接

#define CAT(batman, robin) batman ## robin

#define make_friend(index)  printf("You and %s are friends.\n", CAT(james, index));

int main(int argc, char* argv[])
{
    char* james001="fake James 001";
    char* james007="James Bond";
    char* james110="fake James 110";

    make_friend(001);
    make_friend(007);
    make_friend(110);
    return 0;
}


     首先,这里仍需要将 001、007、110 看作是代码,而不是数字。

     然后再说,通过 CAT 将 james 和 index 拼合成为 james001、james007、james110 三个变量(代码),在 print 过程中打印出来。

后续:

     在其他文章里,可能你还会找到 ## 可以拼接字符串, # 也可以。但是实测结果是,在 linux 环境中,无法正常编译。所以为了代码的通用性,最好还是仅将 # 和 ## 作上述两种用途。当然在这个基础之上可以有很多的扩展。

猜你喜欢

转载自blog.csdn.net/davied9/article/details/81902166
今日推荐