strcmp的#定义var不好吗?
我可以比较strcmp中的strcmp的#定义var不好吗?,c,macros,strcmp,C,Macros,Strcmp,我可以比较strcmp中的#define变量和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; } #包括 #包括 #定义var“hello” int main() { ch
#define
变量和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;
}
#包括
#包括
#定义var“hello”
int main()
{
char*p=“你好”;
if(strcmp(p,var)==0)
printf(“相同的\n”);
其他的
printf(“不相同的\n”);
返回0;
}
是否存在与上述示例相同的使用字符定义的风险
#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;
}
#包括
#包括
#定义var“hello”
内部主(空)
{
char*buf=“你好”;
if(strcmp(buf,var)==0)//这好吗
printf(“相同”);
返回0;
}
不要相信我们,相信预处理器的输出
文件“foo.c”
由于标准系统库,因此有大量输出…:
# 5 "foo.c"
int main(void)
{
char *buf="hello";
if(strcmp(buf,"hello")==0)
printf("same");
return 0;
}
正如您所看到的,您的define已经被string文本安全地替换了
当您有疑问时,只需应用此方法来确保(在转换为字符串或连接令牌时更有用,需要避免陷阱)
在您的情况下,还可以避免使用宏并使用:
static const char *var = "hello";
这保证只设置了1次出现的
“hello”
(节省数据内存)。好吧,这个例子不会编译,所以我猜有一个风险,预处理器只是用文本替换您的令牌(也就是说,如果令牌与文本匹配,这在您的代码中不是这样的)@我现在编辑的是will compileThevar
名称非常混乱。它不是一个变量。按照惯例,宏名称通常都是大写的,例如#define FOO“hello”
阅读wikipage on;然后继续阅读和参考。你看起来很困惑!在评论中,我被要求删除#用静态成本定义不确定为什么有些人不喜欢宏。在这种情况下,static const char*
也可以,而且可能更好,因为它可以保证字符串的内存不会重复。@Jean-Françoisfare:如果类型安全代码也可以(例如,您将始终获得相同的字符串,可能会节省内存等),那么永远不要使用宏。是的,在这种情况下,您可以避免它,而不存在任何复制/粘贴问题。宏对于避免复制/粘贴代码构造或标记连接(在某种程度上)非常有用,但这里有一点太过分了(如果您注意到的话,我在回答中添加了这样的结论)
# 5 "foo.c"
int main(void)
{
char *buf="hello";
if(strcmp(buf,"hello")==0)
printf("same");
return 0;
}
static const char *var = "hello";