c - #define var 对 strcmp 不好吗?

标签 c macros strcmp

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

像上面的例子那样用char *来组合#define有什么风险吗?

最佳答案

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

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

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

当你有疑问的时候,就应用这个方法来确定(在转换为字符串或连接 token 时更有用,有陷阱要避免)

在你的情况下,你也可以避免宏并使用:

static const char *var = "hello";

这保证只有 1 次 "hello" 被设置(节省数据内存)。

关于c - #define var 对 strcmp 不好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46282405/

相关文章:

c# - C#、C/C++ 或 Objective-C 中的眼动追踪库

c++ - 函数参数中的 struct 关键字和常量正确性

c - 为什么可以使用任意数量的参数调用未定义参数的函数?

c - 如何在 C 中连接两个字符串宏?

string-comparison - strcmp() 对于相同字符串比较返回不同的值

c - strcmp(字符串比较)到底在做什么?

c - 使用 MPI 发送 glib 哈希表

c++ - 从工厂类创建对象名称的 undefined reference

c++ - 如何用#include 替换这个预处理器宏?

c++ - GDB - strcmp 不工作 : __strcmp_sse2_unaligned