Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stringizing #a in define, why is it bad

#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?

like image 428
user501743 Avatar asked Feb 01 '11 21:02

user501743


People also ask

What is Stringizing operator in C?

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.

What does ## mean in C language?

## 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.

How do you define a string macro?

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.

What is a macro C++?

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.


1 Answers

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
like image 164
EnabrenTane Avatar answered Sep 17 '22 06:09

EnabrenTane