çpreprocessor:如何创建字符文字? [英] C preprocessor: How to create a character literal?

查看:174
本文介绍了çpreprocessor:如何创建字符文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是出于好奇,我想知道是否可以定义,可以把它的参数转换为字符文字宏:

Just out of curiosity, I'd like to know if it is possible to define a macro which can turn its argument into a character literal:

 switch(getchar()) {
   case MYMACRO(A): printf("Received A\n"); break;
   case MYMACRO(a): printf("Received a\n"); break;
   case MYMACRO(!): printf("Received an exclamation mark\n"); break;
   default: printf("Neither a nor A nor !\n"); break;
 }

我的头的顶部有两个可能的解决方案:

Two possible solutions off the top of my head:

枚举所有字符

Enumerating all characters

#define LITERAL_a 'a'
#define LITERAL_b 'b'
...
#define MYMACRO(x) LITERAL_ ## x

这不符合工作MYMACRO(!),因为不是C标识符的有效成分

It doesn't work with MYMACRO(!) because ! is not a valid component of a C identifier.

参数转换成字符串

Convert the parameter into a string literal

#define MYMACRO(x) #x [0]

这涉及到一个指针引用和无效像一个case标签的地方。

It involves a pointer dereference and is invalid in places like a case label.

我不要求一种方式来改进上面的开关语句本身。这只是一个玩具的例子。重复。这只是一个玩具的例子。

推荐答案

下面是我的可能的解决方案:

Here's my possible solution:

#define EVAL(...) __VA_ARGS__
#define Q() '
#define MYMACRO(...) Q()EVAL(__VA_ARGS__)Q()

(可变参数宏用于支持 MYMACRO(,),因为它会被解析为两个空参数。)

(Variadic macros are used to to support MYMACRO(,) because it would be parsed as two empty arguments.)

我不知道这是否code是符合标准的,由于不匹配
不过,我认为这code适用于大多数C99编译器。
然而,这code以下字符不起作用:

I'm not sure if this code is standard-conformant due to the unmatched '. Still, I think this code works on most C99 compilers. However, this code does not work for the following characters:


  • 这也在配合

  • 用于识别参数列表的开始和结束

  • 用于字符串和字符常量

  • \\ ,它需要转义

  • 空白字符,因为它们不是标记

  • ( which has to match with )
  • ) used to identify the start and end of the argument list
  • ' and " used for string literals and character constants
  • \, which needs escaping
  • Whitespace characters, because they are not tokens

我相当肯定,有没有解决方案,为,因为如果被允许,编译器将不得不改变方式宏参数解析。

I'm fairly sure that there's no solution that work for (, ), ' or ", because if this was allowed, the compiler would have to change the way macros arguments are parsed.

这篇关于çpreprocessor:如何创建字符文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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