当将STRCMP不会返回-1,0或1? [英] When will strcmp not return -1, 0 or 1?
问题描述
从手册页:
该STRCMP()和STRNCMP()函数返回小于,等于少一个整数
如果s1(或其前n个字节)被发现,或大于零,
分别为小于,匹配,或者是大于s2
The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.
例子$ C $(打印 -15
我的机器上,交换TEST1和TEST2反转值)C在C:
Example code in C (prints -15
on my machine, swapping test1 and test2 inverts the value):
#include <stdio.h>
#include <string.h>
int main() {
char* test1 = "hello";
char* test2 = "world";
printf("%d\n", strcmp(test1, test2));
}
<击>我发现这个code 一>(从<一所href=\"http://stackoverflow.com/questions/13560037/effcient-way-to-find-longest-duplicate-string-for-python-from-programming-pearl/13560449#13560449\">this问题)依靠的不是-1,0和1(它使用的qsort
的返回值等STRCMP是东西值)。对我来说,这是很可怕的风格和依赖于未记录的功能。击>
I found this code (taken from this question) that relies on the values of strcmp being something other than -1, 0 and 1 (it uses the return value in qsort
). To me, this is terrible style and depends on undocumented features.
我想我有两个相关的问题:
I guess I have two, related questions:
- 有什么在C标准,定义什么返回值之外小于,大于或等于零?如果没有,什么是标准的实现呢?
- 是跨Linux,Windows和BSD系统? 一致的返回值
- Is there something in the C standard that defines what the return values are besides less than, greater than, or equal to zero? If not, what does the standard implementation do?
- Is the return value consistent across the Linux, Windows and the BSDs?
编辑:
离开我的电脑5分钟后,我意识到,其实也有与有问题的code没有错误。我打出了我阅读注释/应答前想通了部分,但我离开他们那里保持的评论相关。我认为这仍然是一个有趣的问题,并可能会导致对使用其他语言总是返回-1,0或1的程序员打嗝(例如Python的似乎要做到这一点,但它不记录这样)。
After leaving my computer for 5 minutes, I realized that there is in fact no error with the code in question. I struck out the parts that I figured out before reading the comments/answers, but I left them there to keep the comments relevant. I think this is still an interesting question and may cause hiccups for programmers used to other languages that always return -1, 0 or 1 (e.g. Python seems to do this, but it's not documented that way).
FWIW,我认为,依靠比记录的行为以外的东西是不好的风格。
FWIW, I think that relying on something other than the documented behavior is bad style.
推荐答案
在C99标准
7.21.4.2 The strcmp function
的 STRCMP
函数返回一个整数大于,等于或小于零
,
相应地作为字符串指向S1大于,等于,或小于字符串s2指向到。
" The strcmp
function returns an integer greater than, equal to, or less than zero
,
accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2. "
这意味着标准不保证有关 1
, 0
或 1
它可以根据操作系统的不同而不同。
It means standard doesn't guarantee about the -1
,0
or 1
it may vary according to operating systems.
你所得到的值是 W的
和 ^ h
是 15的区别
。
在你的情况你好
和全球
所以'H' - 'W'= -15℃; 0
和这就是为什么STRCMP retuns -15
这篇关于当将STRCMP不会返回-1,0或1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!