在define中对#a进行字符串化,为什么不好
#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 是问题所在。它确实有效,那么为什么它是危险的呢?
#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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为它绕过了类型安全。 时会发生什么
当有人讨厌你并进行
print_int("5412");
输出because it bypasses type safety. What happens when someone hates you and goes
print_int("5412");
outputs
我认为这一点也不坏。 stringtize 运算符对于编写断言等宏非常有用:
您可能会滥用任何有用的功能。我曾经有一个好主意,通过编写以下内容来“简化”Qt Atoms:
所以你可以说
ATOM(MPEG)
并得到('M' << 24 | 'P' < 24 | 'P' < <16 | ...)。事实上,它运行得很好,gcc 可以从中生成整数常量...有时...现在这很邪恶!
I don't think it's bad at all. The stringtize operator is very useful for writing macros like assertions:
You an abuse any useful feature. I once had the bright idea to "simplify" Qt Atoms by writing:
So you could say
ATOM(MPEG)
and get('M' << 24 | 'P' << 16 | ...)
. In fact, it worked well enough that gcc could produce integer constants from it... Sometimes... Now that was evil!预处理器语句通常被认为是邪恶的。当我说:
Preprocessor statements are generally considered evil. Bad things will happen when I say: