about operation of unsigned type

S

Steven

Hello, everyone!

I find a version of strcpy(), I don't know why it return the unsigned
char value.
Can I change it into return *s1-*s2?

int strcmp(const char *s1, const char *s2)
{
while (*s1 == *s2)
{
if (*s1 == 0)
return 0;
s1++;
s2++;
}
return *(unsigned const char *)s1 - *(unsigned const char *)(s2);
}
 
B

Barry Schwarz

Hello, everyone!

I find a version of strcpy(), I don't know why it return the unsigned
char value.

In discussing integer conversions, paragraph 6.3.1.8 says that if the
operands have the same type, no conversion is performed. Both
operands in your subtraction have type unsigned char. Therefore,
unsigned subtraction is performed. The result will always be
non-negative. This result is then converted to a non-negative int and
returned to the calling program.
Can I change it into return *s1-*s2?

You cannot guarantee that this expression will not overflow.
int strcmp(const char *s1, const char *s2)

This function name belongs to the implementation. You are not allowed
to use it for yourself.
{
while (*s1 == *s2)
{
if (*s1 == 0)
return 0;
s1++;
s2++;
}
return *(unsigned const char *)s1 - *(unsigned const char *)(s2);
}

Why not
return *s1 > *s2 ? 1 : -1;


Remove del for email
 
A

Antoninus Twink

Seems the most reasonable choice. We don't have the problem of
overflow over here.

On the other hand, you do have the problem that the compiler (depending
on its optimization capabilites) could well implement this using a
couple of jump operations instead of just a few moves and a single sub.
That's an issue in a standard library function that will be used a lot
by a lot of people.
 
B

Barry Schwarz

No, it says that if the *promoted* operands have the same
type, no conversion is performed.


No. `unsigned char' operands promote to `int' (on most
systems) or to `unsigned int' (if UCHAR_MAX > INT_MAX), so
the implementation determines whether signed (usually) or
unsigned (sometimes) arithmetic is used.
True, I obviously missed the lead-in paragraph in searching for the
conversion rules.

Which raises the question of why the OP believes that his function is
returning an unsigned value.


Remove del for email
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top