【问题标题】:Is #define var bad with strcmp?#define var 对 strcmp 不好吗?
【发布时间】:2017-09-18 14:55:41
【问题描述】:

我可以在 strcmp 中比较#definevarible 和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 *如上例有什么风险吗?

【问题讨论】:

  • 好吧,这个例子不会编译,所以我猜有这个风险
  • 不,预处理器只是用文字替换您的标记(也就是说,如果标记与文字匹配,您的代码中不是这种情况)
  • @UnholySheep 我现在编辑这将编译
  • var 的名称非常令人困惑。它不是一个变量。按照惯例,宏名称通常都是大写的,例如#define FOO "hello"
  • 阅读C preprocessor上的维基页面;然后阅读documentation of cpp 并参考preprocessor。你看起来很困惑!

标签: c macros strcmp


【解决方案1】:

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

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

保证"hello" 只出现1 次(节省数据内存)。

【讨论】:

  • 在审查中,我被要求删除带有静态成本的#define,不确定原因
  • 有些人不喜欢宏。在这种情况下,static const char * 也可以,而且可能会更好,因为它可以保证字符串的内存不重复。
  • @Jean-FrançoisFabre:如果类型安全代码也可以,则永远不要使用宏(例如,您将始终获得相同的字符串,可能会节省内存等)。
  • 是的,在这种情况下,您可以避免它而不会出现任何复制/粘贴问题。宏非常适合避免复制/粘贴代码结构或令牌连接(在某种程度上),但这是矫枉过正(如果你注意到,我在我的回答中添加了这样的结论)
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-25
    • 2010-11-13
    • 2018-09-14
    • 2017-01-02
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    相关资源
    最近更新 更多