宏它打印一个前pression和评估它(与__STRING) [英] Macro which prints an expression and evaluates it (with __STRING)

查看:157
本文介绍了宏它打印一个前pression和评估它(与__STRING)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关学习和示范,我需要它打印它的参数计算它的宏。我怀疑这是一个很常见的情况,甚至可能一个常见问题,但我无法找到实际的引用。

我目前的code是:

 的#define PRINT(表达式)(fprintf中(标准输出,%S  - >%d个\\ N,__STRING(表达式),(表达式)))

和则:

  PRINT(X安培; 0×01);

它工作正常,但我不知道的__STRING宏观的法律地位,特别是因为它是在私人空间__

所以,我的问题:


  1. 有没有更好的方式来写这个宏?

  2. 是__STRING标准/大/邪?

  3. 如何利用现有的搜索工具来查找有关__STRING? SO的搜索引擎只是将搜索任何包含字符串: - (


解决方案

您可以使用#preprocessor令牌,该令牌的RHS参数转换为字符串:

 的#include<&stdlib.h中GT;
#包括LT&;&stdio.h中GT;STR的#define(X)#X
#定义打印(表达式)(fprintf中(标准输出,%S - >%d个\\ N,STR(表达式),(表达式)))INT主要(无效)
{
    INT X = 7;    PRINT(X安培; 0×01);    返回EXIT_SUCCESS;
}

2),这肯定不是标准,这是我第一次碰到它;并不奇怪,因为它似乎并没有做的比上述STR()宏得多,在第一一目了然。

3)谷歌似乎很好地工作。

For learning and demonstrating, I need a macro which prints its parameter and evaluates it. I suspect it is a very common case, may be even a FAQ but I cannot find actual references.

My current code is:

#define PRINT(expr) (fprintf(stdout, "%s -> %d\n", __STRING(expr), (expr)))

and then:

PRINT(x & 0x01);

It works fine but I am not sure of the legal status of the __STRING macro, specially since it is in the private __ namespace.

So, my questions:

  1. Is there a better way to write this macro?
  2. Is __STRING standard/great/evil?
  3. How to use existing search tools to find about __STRING? SO's search engine just searches anything containing string :-(

解决方案

You can use the # preprocessor token which converts its RHS argument to a string literal:

#include <stdlib.h>
#include <stdio.h>

#define STR(x) #x
#define PRINT(expr) (fprintf(stdout, "%s -> %d\n", STR(expr), (expr)))

int main(void)
{
    int x = 7;

    PRINT(x & 0x01);

    return EXIT_SUCCESS;
}

2) It's definitely not standard, and this is the first time I've come across it; not surprising as it doesn't seem to do much more than the STR() macro above, at a first glance.

3) Google seems to work fine.

这篇关于宏它打印一个前pression和评估它(与__STRING)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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