strchr declaration

T

ts

Hello all,

Can somebody explain why strchr is declared the way it is? Here is
the declaration:

char *strchr(const char *s, int c);

Mainly I do not understand why the second parameter has the 'int'
type. From my knowledge it is not even portable. On a machine where
'char' has the same size as an 'int' and where 'char' has the same
behaviour as an 'unsigned char' the following piece of code could not
work as expected:

{
char c;
char *p;

/* some statements here initializing c */

p = strchr(my_string, c);
}

I am not a portability expert, so probably I am wrong. But having the
second parameter of 'char' type is less confusing and does not change
the behaviour at all.

thx
cristi
 
C

Chris Dollin

ts said:
Can somebody explain why strchr is declared the way it is? Here is
the declaration:

char *strchr(const char *s, int c);

Mainly I do not understand why the second parameter has the 'int'
type.

Historical reasons, I believe. Remember that `strchr` existed before
function prototypes did, and that a character literal such as 'X'
has type /int/ not type /char/. Suppose (as would be the case for
a /lot/ of code move from pre-Standard to post_Standard) that
`strchr` is declared without a prototype. Then the default argument
promotions apply, so `char`s get promoted to `int`s, so if the
/definition/ of `strchr` has second argument `char` the effects are
undefined. This is a Bad Thing.
From my knowledge it is not even portable. On a machine where
'char' has the same size as an 'int'

.... various problems arise in any case, if I recall correctly. An
easy fix is to make such an implementation freestanding, in which
case they don't have to provide the C standard library [1]!
I am not a portability expert, so probably I am wrong. But having the
second parameter of 'char' type is less confusing and does not change
the behaviour at all.

It would be, but for history; and it does, even if only by a little.

[1] Perhaps this is "fixed" as in "You're well and truly fixed.".
 

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

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top