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

时间:2017-09-18 14:55:42

标签: c macros strcmp

我可以在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;
}

上面的示例中是否存在与#define相关的风险comapre char *

2 个答案:

答案 0 :(得分:5)

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

档案“foo.c”

@IBInspectable var adjustFontSize : Bool {
    set { titleLabel?.adjustsFontForContentSizeCategory = newValue } 
    get { return titleLabel!.adjustsFontForContentSizeCategory  }

现在:

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

保证只设置了1次static const char *var = "hello"; (保存数据存储器)。

答案 1 :(得分:2)

不,comapre #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;    
    }