宏它打印一个前pression和评估它(与__STRING) [英] Macro which prints an expression and evaluates it (with __STRING)
问题描述
有关学习和示范,我需要它打印它的参数和计算它的宏。我怀疑这是一个很常见的情况,甚至可能一个常见问题,但我无法找到实际的引用。
我目前的code是:
的#define PRINT(表达式)(fprintf中(标准输出,%S - >%d个\\ N,__STRING(表达式),(表达式)))
和则:
PRINT(X安培; 0×01);
它工作正常,但我不知道的__STRING宏观的法律地位,特别是因为它是在私人空间__
所以,我的问题:
- 有没有更好的方式来写这个宏?
- 是__STRING标准/大/邪?
- 如何利用现有的搜索工具来查找有关__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:
- Is there a better way to write this macro?
- Is __STRING standard/great/evil?
- 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屋!