【问题标题】:When does !strcmp(a,b) evaluate as true?!strcmp(a,b) 什么时候评估为真?
【发布时间】:2016-06-26 18:29:53
【问题描述】:

如果我们有下面的代码,!strcmp(a,b) 是什么意思?我知道如何使用strcmp(a,b),我知道如果a = b,它返回0,如果a<b 它返回-1,如果a>b 它返回1! 符号应该否定那个函数,那么下面的代码什么时候返回 i?我很困惑。

 for(i=1;i<var;i++) 
     if(!strcmp(s,anotherVar[i]))
         return i;   

【问题讨论】:

  • 给定x(其中x是一个int),!x是什么意思?
  • if(!strcmp(s,anotherVar[i])) 表示“如果字符串相同”。
  • @ClaudiuM !falsefalse?
  • @ClaudiuM 所以现在再次回答这个问题,给定x(其中 x 是一个 int),当您不能仅仅假设 x = true 时,!x 的含义是什么?
  • @hvd 你要求的 :) @Claudiu !x 整数是 x != 0,希望你现在明白了。

标签: c


【解决方案1】:

想想数值的实际含义。当您将数字视为布尔条件时,0 被评估为false;其他任何东西都被评估为true。所以!0 计算为true,而!n 计算为false 对于n 的所有非零值。

换句话说,!strcmp(s,anotherVar[i])sanotherVar[i] 相同时为真(因为strcmp 返回0),但在它们不同时为假(因为strcmp 返回非零值)。

这里是a live, online demo,使用以下代码:

#include <stdio.h>

int main(void) {
    char * a = "hello";
    char * b = "world";
    char * c = "hello";

    if (!strcmp(a,b)) {
        printf("true for a and b\n");
    } else {
        printf("false for a and b\n"); // this runs
    }

    if (!strcmp(a,c)) {
        printf("true for a and c\n"); // this runs
    } else {
        printf("false for a and c\n");
    }

    return 0;
}

输出是:

false for a and b
true for a and c

【讨论】:

  • 我要补充一点,尽管任何非零值都被视为真,但逻辑和比较运算符总是返回 1 为真......例如。 82 &amp;&amp; 144 计算结果为 1,而不是其他一些非零值。
  • @ClaudiuM 很高兴能为您提供帮助。否决票可能是因为这个问题很容易通过一些研究来回答。这个网站允许投反对票是有原因的,反对票不会让这里的人“坏”。
【解决方案2】:

如果strcmp 返回0!strcmp 将返回true

if(0) //false 
if(4) //true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 2014-05-19
    • 2011-02-14
    • 2014-02-16
    • 1970-01-01
    相关资源
    最近更新 更多