Trying to create a simple function that would look for a single char in a string "like strchr() would", i did the following:
char* findchar(char* str, char c)
{
char* position = NULL;
int i = 0;
for(i = 0; str[i]!='\0';i++)
{
if(str[i] == c)
{
position = &str[i];
break;
}
}
return position;
}
So far it works. However, when i looked at the prototype of strchr():
char *strchr(const char *str, int c);
The second parameter is an int? I'm curious to know.. Why not a char? Does this mean that we can use int for storing characters just like we use a char?
Which brings me to the second question, i tried to change my function to accept an int as a second parameter... but i'm not sure if it's correct and safe to do the following:
char* findchar(char* str, int c)
{
char* position = NULL;
int i = 0;
for(i = 0; str[i]!='\0';i++)
{
if(str[i] == c) //Specifically, is this line correct? Can we test an int against a char?
{
position = &str[i];
break;
}
}
return position;
}
Description. The strchr() function finds the first occurrence of a character in a string. The character c can be the null character (\0); the ending null character of string is included in the search. The strchr() function operates on null-ended strings.
In order to preserve and reproduce the "traditional" functionality of strchr , as described above, we have no other choice but to declare the parameter of strchr as an int and explicitly convert it to char inside the function. This is exactly what you observe in the code you quoted.
The strchr() function returns a pointer to the first occurrence of c that is converted to a character in string. The function returns NULL if the specified character is not found.
Before ANSI C89, functions were declared without prototypes. The declaration for strchr
looked like this back then:
char *strchr();
That's it. No parameters are declared at all. Instead, there were these simple rules:
int
are converted to int
double
So when you called strchr
, what really happened was:
strchr(str, (int)chr);
When ANSI C89 was introduced, it had to maintain backwards compatibility. Therefore it defined the prototype of strchr
as:
char *strchr(const char *str, int chr);
This preserves the exact behavior of the above sample call, including the conversion to int
. This is important since an implementation may define that passing a char
argument works differently than passing an int
argument, which makes sense on 8 bit platforms.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With