In this function, why do we need to cast with unsigned char? Can't we cast with char and get the same result since both have a range of "255"? Why choose unsigned char?
Suppose there is no ASCII code equal to -126. I can say the same about 255; both will give you a garbage value. If you tell me we choose it because we are working with bytes, and the maximum value of it is 255, I would say we are just comparing. So, in s1 and s2, the result will always be an ASCII code. Why do we choose unsigned char?
#include "libft.h"
int ft_strncmp(const char *s1, const char *s2, size_t n)
{
size_t i;
i = 0;
if (n == 0)
return (0);
while (i < n && (s1[i] != '\0' || s2[i] != '\0'))
{
if (s1[i] != s2[i])
return ((unsigned char)s1[i] - (unsigned char)s2[i]);
i++;
}
return (0);
}
The standard C library performs string functions as if the the characters were
unsigned char.As a
charmay be signed or unsigned, subtracting 2charhas a different result than 2unsigned charwhen one of thecharis negative. So casting tounsigned charforms a difference like the C library.Pedantic
On rare implementations the width of
charandintare the same, so subtracting to return the difference with the correct sign risks overflow. Instead do multiple compares.With strings, and the nearly obsolete non-2's complement formats,
((unsigned char *)s1)[i]can differ from(unsigned char)s1[i]and is the preferred form.Below fixes both issues:
or