By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,852 Members | 2,219 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,852 IT Pros & Developers. It's quick & easy.

strchr declaration

P: n/a
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
Mar 14 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
ts <cr****@medialab.sissa.itwrote:
Can somebody explain why strchr is declared the way it is? Here is
the declaration:

char *strchr(const char *s, int c);
This has been asked here before. Have a look at:

Message-ID: <o2LIa.12908$KF1.274554@amstwist00>
(http://groups.google.de/group/comp.l...658a994d3c28f/)
HTH
Flo
Mar 14 '07 #2

P: n/a
ts wrote:
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.".

--
Chris "electric hedgehog" Dollin
"What I don't understand is this ..." Trevor Chaplin, /The Beiderbeck Affair/

Mar 14 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.