Strange behaviour of strchr in C++

Joe Buck Joe.Buck@synopsys.COM
Tue Feb 28 00:07:00 GMT 2006


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.

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.

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*'


> 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).

> 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.




More information about the Libstdc++ mailing list