c - 在定义中将#a 字符串化,为什么不好

标签 c printf c-preprocessor

#include <stdio.h>
#define print_int(a) printf("%s : %d\n",#a,(a))
int main(void) {
    int y = 10;
    print_int(y);
    return 0;
}

我正在上课,并被要求解释为什么这是不好的......所以我猜想字符串化 #a 是问题所在。它确实有效,那么为什么它很危险呢?

最佳答案

因为它绕过了类型安全。当有人讨厌你并去 print_int("5412");

时会发生什么
#include <stdio.h>
#define print_int(a) printf("%s : %d\n",#a,(a))
int main(void) {
    print_int("1123123");
    return 0;
}

输出

$ 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

关于c - 在定义中将#a 字符串化,为什么不好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4868422/

相关文章:

c - C 结构中的默认值

C++ qsort中的size参数有什么作用

c - printf 格式(%d 与 %u)

c++ - C printf跨平台格式无警告

c - C 程序中设置的预处理器指令值

c - "too large"对象是否具有自动存储持续时间未定义的行为?

c - 新手 : C syntax error when compiling

c - printf 中的 %s 格式说明符

preprocessor - 哪些 C 系列语言有预处理器?

c++ - 如何在 C 宏中使用#if,#else,#endif...