gpt4 book ai didi

c++ - 为什么 strcmp 返回 int 而不是 char?

转载 作者:IT老高 更新时间:2023-10-28 22:32:01 32 4
gpt4 key购买 nike

据我所知,charint 等变量类型之间的唯一区别是它们占用的内存量。我猜他们在调节他们持有的变量代表什么方面没有任何作用。如果这是真的,在 here ,我在 strcmp 看到了以下内容:

The strcmp function compares the string s1 against s2, returning a value that has the same sign as the difference between the first differing pair of characters (interpreted as unsigned char objects, then promoted to int).

我想问为什么结果会提升为int?由于正在比较 char,因此它们的差异在所有情况下都适合 char。那么不是将结果提升为 int 只是在结果末尾附加一堆 0 吗?那么,为什么要这样做呢?

最佳答案

char 可以签名也可以不签名。 strcmp 必须返回有符号类型,这样如果差为负,则可以为负。

更一般地说,int 更适合用于传递和返回简单数值,因为它被定义为此类值的“自然”大小,并且在某些平台上,处理比较小的值更有效类型。

关于c++ - 为什么 strcmp 返回 int 而不是 char?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30487800/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com