Strange behaviour of strchr in C++
Jonathan Wakely
jwakely.gcc@gmail.com
Thu Mar 2 10:12:00 GMT 2006
On 28/02/06, Mateusz Łoskot <mateusz@loskot.net> wrote:
> Joe Buck wrote:
> > Just include <cstring> and call strchr as if the correct prototypes
> > were provided. For valid code, the right thing will happen. The
> > only issue is that the compiler will not detect cases where you
> > use strchr to silently get a char* from a const char*. So all you
> > really lose is an error check.
>
> That's what I'm asking for.
> So, in C++ program I should use C++ version of strchr, even if I can use
> C version without any error check.
Yes. If you take advantage of the "buggy" C version your code will not
be portable and may not be valid. That's true in C as well, this
compiles but is not correct:
#include <string.h>
const char s[] = "Hello, world!";
int main() { *strchr(s, 'H') = 'Y'; return 0; }
Don't do this - it's obviously wrong.
If you don't try to do this it shouldn't matter much that GCC does not
provide the correct C++ overloads.
> And using C version of strchr in C++ program should be seen as
> incorrect. You know, someone can still argue "gcc compiles my code, so
> it's correct" and I'd like to be sure what should I tell her/him :-)
1) GCC is not the arbiter of what is correct.
2) There are lots of programs that compile but are not correct.
here's another one:
int main(int argc, char** argv) { return *argv[argc]; }
The fact GCC compiles this does not make it correct.
jon
More information about the Libstdc++
mailing list