我可以在 strcmp 中比较 #define
varible 和 char *
吗?
#include<stdio.h>
#include<string.h>
#define var "hello"
int main()
{
char *p ="hello";
if(strcmp(p,var)==0)
printf("same\n");
else
printf("not same\n");
return 0;
}
像上面的例子那样用char *
来组合#define
有什么风险吗?
最佳答案
不要相信我们,相信预处理器输出
文件“foo.c”
#include <stdio.h>
#include <string.h>
#define var "hello"
int main(void)
{
char *buf="hello";
if(strcmp(buf,var)==0) // Is this good
printf("same");
return 0;
}
现在:
gcc -E foo.c
很多输出是因为标准系统库...:
# 5 "foo.c"
int main(void)
{
char *buf="hello";
if(strcmp(buf,"hello")==0)
printf("same");
return 0;
}
如您所见,您的定义已安全地替换为字符串文字。
当你有疑问的时候,就应用这个方法来确定(在转换为字符串或连接 token 时更有用,有陷阱要避免)
在你的情况下,你也可以避免宏并使用:
static const char *var = "hello";
这保证只有 1 次 "hello"
被设置(节省数据内存)。
关于c - #define var 对 strcmp 不好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46282405/