#define var 对 strcmp 不好吗?

Is #define var bad with 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;
}

如上例#definechar *比较有风险吗?

不,将#define 与char* 进行比较完全没有风险。

    #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;    
    }

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

文件"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

大量输出,因为标准系统库...:[=​​15=]

# 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"(节省数据内存)。