加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用strcmp #define var是不是很糟糕?

发布时间:2020-12-16 10:07:59 所属栏目:百科 来源:网络整理
导读:我可以在strcmp中比较#definevarible andchar *,如下所示. #includestdio.h#includestring.h#define var "hello"int main(){char *p ="hello";if(strcmp(p,var)==0)printf("samen");elseprintf("not samen");return 0;} 有没有任何风险comapre #define wit
我可以在strcmp中比较#definevarible andchar *,如下所示.

#include<stdio.h>
#include<string.h>
#define var "hello"
int main()
{
char *p ="hello";
if(strcmp(p,var)==0)
printf("samen");
else
printf("not samen");
return 0;
}

有没有任何风险comapre #define with char *如上例所示?

解决方法

不要相信我们,相信预处理器输出

档案“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;
}

如您所见,您的定义已被字符串文字安全地替换.

如果您有疑问,只需应用此方法以确保(在转换为字符串或连接令牌时更有用,有些陷阱可以避免)

在您的情况下,您还可以避免宏并使用:

static const char *var = "hello";

这保证只设置了1次“hello”(保存数据存储器).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读