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

Roh*_*ngh 3 c macros strcmp

我可以比较#definevarible和char *strcmp如下.

#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;
}
Run Code Online (Sandbox Code Playgroud)

如上例所示#define,是否存在任何风险comapre char *

Jea*_*bre 5

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

档案"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;    
}
Run Code Online (Sandbox Code Playgroud)

现在:

gcc -E foo.c
Run Code Online (Sandbox Code Playgroud)

由于标准系统库然后有很多输出...:

# 5 "foo.c"
int main(void)
{
    char *buf="hello";

    if(strcmp(buf,"hello")==0)
        printf("same");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

static const char *var = "hello";
Run Code Online (Sandbox Code Playgroud)

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