The standard function strstr
is used to find the location of a sub-string in a string. Both the arguments of the function are of const char *
type, but the return type is char *
.
I would like to know how a standard function is implemented violating the const-correctness.
Return Value The strstr() function returns a pointer to the beginning of the first occurrence of string2 in string1. If string2 does not appear in string1, the strstr() function returns NULL. If string2 points to a string with zero length, the strstr() function returns string1.
Return value The strstr() function returns the part of the input string searched for, or false if it fails to find the searched string.
All the const char * is telling you is that strstr is not going to modify the string you pass into it. Whether you modify the returned string or not is up to you as it is your string!
(Search String for Substring) In the C Programming Language, the strstr function searches within the string pointed to by s1 for the string pointed to by s2. It returns a pointer to the first occurrence in s1 of s2.
All the const char *
is telling you is that strstr
is not going to modify the string you pass into it.
Whether you modify the returned string or not is up to you as it is your string!
In C++ this has been changed by overloading the method and having two versions, the const
input version has a const
output.
In C it doesn't have quite that level of safety built in for you and assumes you know yourself whether you should be modifying the returned string.
C allows pointing to memory with const or non-const pointers, regardless if the object was defined with the const qualifier or not.
6.5 Expressions
- An object shall have its stored value accessed only by an lvalue expression that has one of the following types:
— a qualified version of a type compatible with the effective type of the object,
The prototype of strstr in C is:
char *strstr(const char *s1, const char *s2);
The returned pointer, if valid, points to string s1. This can be achieved with a cast:
const char safe = 's' ; char* careful = ( char* )&safe ;
The problem is modifying that memory.
6.7.3 Type qualifiers
- If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.
Since you created the string, you should know whether you can modify it or not, therefore you can accept the return value with a pointer to const, to avoid any problems:
const char* find = strstr( ... ) ;
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