【问题标题】:Comparing string with if condition [duplicate]将字符串与if条件进行比较[重复]
【发布时间】:2020-01-27 14:53:01
【问题描述】:

我正在使用 if 条件比较字符串,但第二个 if 条件失败。在这些比较案例中,失败的原因是什么?编译器级别会发生什么?

char *c = "test";
char a[] = "test";

if(c=="test")
{
    printf("Hai\n");
    if(a=="test")
    printf("Bye\n");
}

【问题讨论】:

  • 你真的应该遵循一个教程。 strcmp 是您所需要的。
  • c=="test" 正在比较两个指针,在您的情况下(可能)总是相等的。 a=="test" 也比较两个指针,但它们永远不会相等。
  • 或者更好的是,阅读good book.。
  • 所以用if(c == "test")代替if(!strcmp(c, "test"))

标签: c if-statement compilation compare


【解决方案1】:

在第一次比较中你应该得到一个警告:

警告:与字符串文字比较的结果未指定

但是它返回 true 因为您正在比较两个指针到字符串文字,据我所知,女巫总是相同的。 取以下代码:

#include <stdio.h>
#include <string.h>

int main(void) {
  char *c = "test";
  char a[] = "test";

  printf("%p\n%p\n%p", c, a, "test");
}

结果将是:

0x4005f4

0x7ffedb3caaf3

0x4005f4

如你所见,指针确实是一样的。

也就是说,== 在 C 中不用于比较字符串,您应该使用 strcmp()。

#include <stdio.h>
#include <string.h>

int main(void) {
  char *c = "test";
  char a[] = "test";

  if(!strcmp(c, "test"))
  {
    printf("Hai\n");
    if(!strcmp(a, "test"))
      printf("Bye\n");
  }
}

【讨论】:

  • 我会将c == "test" is not used in C 更改为== is not used in C to compare strings。
猜你喜欢
  • 2021-07-10
  • 1970-01-01
  • 2011-10-19
  • 2012-11-27
  • 1970-01-01
  • 2014-11-08
  • 1970-01-01
  • 2016-07-08
  • 2015-08-14
相关资源
最近更新 更多