代码之家  ›  专栏  ›  技术社区  ›  Rohini Singh

strcmp的#define var坏吗?

  •  3
  • Rohini Singh  · 技术社区  · 8 年前

    我能比较一下吗 #define 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;
    }
    

    有什么风险吗 字符* 如上例所示?

    2 回复  |  直到 8 年前
        1
  •  5
  •   Jean-François Fabre    8 年前

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

    文件“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" 已设置(保存数据内存)。

        2
  •  2
  •   Aashish Kumar    8 年前

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