gpt4 book ai didi

c - 使用 unsigned char 和 char

转载 作者:太空狗 更新时间:2023-10-29 15:17:24 24 4
gpt4 key购买 nike

看了很多strCmp()的实现,发现大部分指针的实现都是用unsigned char完成的

我的问题是,为什么在返回时使用“unsigned”,即使我们不使用它也会得到相同的结果(基于我所做的测试)?

如果我不使用它,我会得到某些值的错误结果吗?

最后,char默认是无符号的还是有符号的?

例子一

int strCmp(const char* s1, const char* s2)
{
while(*s1 && (*s1 == *s2))
{
s1++;
s2++;
}
return *(const unsigned char*)s1 - *(const unsigned char*)s2;
}

示例 2

int strCmp(const char *S1, const char *S2)
{

for(; *S1 == *S2; ++S1, ++S2)
if(*S1 == 0)
return 0;
return *(unsigned char *)S1 < *(unsigned char *)S2 ? -1 : 1;
}

最佳答案

My question is why "unsigned" used in return even though if we didn't use it we will get the same result (based on the tests I did)?

算术是用 int 类型完成的,所以如果 char 是有符号的,你会因为符号扩展而得到错误的负字符值他们。

示例:假设您的字符为 8 位宽并使用 2 的补码签名。那么代码点 128 处的字符将具有 -128 的整数值,因此比较小于范围 [0,127] 中的任何字符,这不是您想要的。转换为 unsigned char 首先确保整数值为 128

Lastly, is char unsigned or signed by default?

事实上,这是定义的实现。因此,请明确使用 unsigned char 来确定。

关于c - 使用 unsigned char 和 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49655991/

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