Strange behaviour of strchr in C++

Mateusz Łoskot mateusz@loskot.net
Tue Feb 28 00:17:00 GMT 2006


Joe Buck wrote:
> On Tue, Feb 28, 2006 at 12:43:30AM +0100, Mateusz Łoskot wrote:
> 
>>I'd like to explan some issue with strchr function in C++.
>>AFAIK, there is only one version of strchr in ANSI C:
>>
>>char *  strchr ( const char * string, int c );
>>
>>ANSI C++ standard specifies two versions:
>>
>>const char * strchr ( const char * string, int c );
>>      char * strchr (       char * string, int c );
>>
>>Those two versions are specified *instead* of the one in ANSI C.
> 
> 
> Yes, it seems this is a bug, though it might be platform-dependent.

I have only access to Linux or Windows.

> It appears that the problem is in the headers; despite the ISO
> requirement, doing
> 
> #include <cstring>
> 
> on a GNU/Linux RHEL 3 system provides the C-style declaration, for
> versions 3.2.3, 4.0, and 4.1-pre.

I also asked on polish pl.comp.lang.c group and my friend there 
suggested following solution to string.h file:

#ifdef __cplusplus
const char* strchr( const char*, int );
#else
char 	*_EXFUN(strchr,(const char *, int));
#endif

> If instead you write
> 
> const char * strchr ( const char * string, int c );
>       char * strchr (       char * string, int c );
> 
> int main() {
>     const char* c = "abc";
>     char* a;
>     a = strchr(c, 'b');
>     return 0;
> }
> 
> you get
> 
> foo.C: In function `int main()':
> foo.C:7: invalid conversion from `const char*' to `char*'

Yes, that's obvious but I think it would be better to expect correct
behaviour by default, wouldn't it?


>>So, I'd expect that g++ should give me an error message
>>because strchr usage is ambiguous but it compiles without any error.
> 
> 
> There is never a problem with ambiguity because overloading depends
> only on the argument types of the functions, never on the context of
> the call (e.g. what the function result is assigned to).

Yes, you're right.
It's more lack of precision in my description here.

>>My questions are:
>>Are my expectations correct and I should get error message?
>>Is this a bug in libstdc++?
>>Is this a bug in C++ standard?
> 
> 
> It is a libstdc++ problem. Resolving it properly is complicated by the
> separate maintainance of glibc and libstdc++; we don't really have a way
> of building on top of the C interface but making a function disappear.

Does it mean there is no chance to work out some solution to have it 
working correct?

By the way, should it be reported to libstdc++ bugzilla?

Cheers
-- 
Mateusz Łoskot
http://mateusz.loskot.net



More information about the Libstdc++ mailing list