#include <stdio.h>
#define print_int(a) printf("%s : %d\n",#a,(a))
int main(void) {
int y = 10;
print_int(y);
return 0;
}
i am taking a class and have been asked to explain why this is bad... So i guess stringizing #a is the problem. It does work, so why is it dangerous?
The number-sign or "stringizing" operator (#) converts macro parameters to string literals without expanding the parameter definition. It's used only with macros that take arguments.
## is usued to concatenate two macros in c-preprocessor. So before compiling f(var,12) should replace by the preprocessor with var12 and hence you got the output.
We can create two or more than two strings in macro, then simply write them one after another to convert them into a concatenated string. The syntax is like below: #define STR1 "str1" #define STR2 " str2" #define STR3 STR1 STR2 //it will concatenate str1 and str2. Input: Take two strings.
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.
because it bypasses type safety. What happens when someone hates you and goes print_int("5412");
#include <stdio.h>
#define print_int(a) printf("%s : %d\n",#a,(a))
int main(void) {
print_int("1123123");
return 0;
}
outputs
$ gcc test.c
test.c: In function ‘main’:
test.c:4: warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘char *’
$ ./a.out
"1123123" : 3870
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