我知道 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/