Macro which prints an expression and evaluates it (with __STRING)

隐身守侯 提交于 2019-12-10 14:17:18

问题


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 :-(

回答1:


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.




回答2:


Something like

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

is probably what you want. # is the stringification operator.



来源:https://stackoverflow.com/questions/377425/macro-which-prints-an-expression-and-evaluates-it-with-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!