c - strcmp 函数在另一个函数中返回值

标签 c strcmp

我知道 strcmp 返回什么,但我不知道它在此代码中返回什么。

首先我有这个功能:

static int match_str(const void *str1, const void *str2)
{

  return !strcmp((const char *)str1, (const char *)str2); 
//if not equal return 1. 
}

然后我就有了这个

if (match_str) return 1; // not equal so return 
else{  my code goes on} // equal so continue

我不明白的是,如果 str1 等于 str2,则 match_str 应该返回 0。然后代码继续。

但它添加了一个“!”运算符(operator)。看起来如果它们相等 strcmp=0 ,它会返回 "!0 ",这意味着 "!0=1 "。但如果返回到1。似乎如果它们相等,它就会停止。

实际上,如果它们相等,则继续。

我真的很困惑为什么“return !strcmp”有效而不是“return strcmp”,使用'!'的目的是什么?在这里。

谢谢

最佳答案

来自 C 标准##6.5.3.3p5

5 The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E).

>> What I don't understand is if str1 equals to str2, the match_str should returns 0. and then the code moves on.

由于使用!运算符 strcmp在 return 语句 ( return !strcmp(.....) ) 中, match_str()将返回1如果字符串匹配并且 0如果它们不匹配。

>> I really confused why " return !strcmp " works rather than "return strcmp", what is the purpose of using '!' here.

strcmp()返回0如果字符串匹配,如果不匹配则为非零值,因为它按字典顺序比较两个以空结尾的字符串。函数作者match_str()其实很想回来1如果字符串匹配并且似乎考虑到这一点,他/她已为该函数指定了名称( match_str )。 match_str()的来电者函数在使用 match_str() 时应该意识到这一点功能。

if (match_str(str1, str2)) {
    //strings are equal
} else {
    //strings are not equal
}

关于c - strcmp 函数在另一个函数中返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53975249/

相关文章:

c - strlen() 的这个基本重新实现如何找到长度?

c - linux execve,段错误(strcmp_sse42)

c++ - 2 个项目可以在 MS VS 2008 中创建一个 dll 吗?

c - 尝试运行自定义 shell 时出现段错误

c - 使用 execvp() 的问题

c - 即使两个字符串都正常,strcmp 也会崩溃

c - 当没有语法错误时,此代码中的 if 情况不起作用

c - strcmp 对 2 个相同字符串的行为不当

c - 串行端口不发送 NULL 值

c++ - 使用指针相乘矩阵