C中的#和##宏 [英] # and ## macros in C

查看:75
本文介绍了C中的#和##宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

程序1:

#include <stdio.h>
#define foo(x, y) #x #y

int main()
{
  printf("%s\n", foo(k, l)); //prints kl
  return 0;
}

计划2:

#include <stdio.h>
#define foo(m, n) m ## n

int main()
{
  printf("%s\n", foo(k, l)); //compiler error
}

为什么两个程序的输出都有这种变化? 这两个程序之间确切的区别是什么?

Why such variation in the output of both programs? What is the exact difference between these two programs?

推荐答案

是 字符串化" 操作符;事实证明它的参数成一个字符串.

# is the "stringizing" operator; it turns its argument into a string literal.

##是令牌粘贴"运算符;它加入它的两个参数为单个令牌,不一定字符串文字.

## is the "token-pasting" operator; it joins its two arguments into a single token, not necessarily a string literal.

一个例子:

#include <stdio.h>

#define foo(m, n) m ## n

int main(void) {
    char *kl = "token pasting";
    printf("%s\n", foo(k, l));
}

其中打印:

token pasting

这篇关于C中的#和##宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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