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:
Here we will see how to define a macro called PRINT(x), and this will print whatever the value of x, passed as an argument. To solve this problem, we will use the stringize operator. Using this operator the x is converted into string, then by calling the printf() function internally, the value of x will be printed.
Macros and its types in C/C++ A macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro.
Something like
#define PRINT(expr) (fprintf(stdout, "%s -> %d\n", #expr, (expr)))
is probably what you want. # is the stringification operator.
You can use the # preprocessor token which converts the parameter following it 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;
}
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.
Google seems to work fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With