【发布时间】: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