Stringising #a in determining why it is 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 take a class and I was asked to explain why this is bad ... Therefore, I think the line #a is the problem. It works, so why is it dangerous?

+4
source share
3 answers

as 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; } 

exits

 $ 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 
+3
source

I do not think this is bad. The stringtize operator is very useful for writing macros, such as statements:

 #define assert(x) do { if (!(x)) { printf("assert failed: %s\n", #x); } } while (0) 

You are abusing any useful feature. I once had a bright idea to “simplify” Qt Atoms by writing:

 #define ATOM(x) (((#x)[0] << 24) | ((#x)[1] << 16) | ... 

So you can say ATOM(MPEG) and get ('M' << 24 | 'P' << 16 | ...) . In fact, it worked well enough that gcc could generate whole constants from it ... Sometimes ... Now it was evil!

+2
source

Preprocessor statements are usually considered evil. Bad things will happen when I say:

 int a = 15; print_int(a++); 
+1
source

Source: https://habr.com/ru/post/1338005/


All Articles