This is the mail archive of the
libstdc++@gcc.gnu.org
mailing list for the libstdc++ project.
Re: Strange behaviour of strchr in C++
- From: "Jonathan Wakely" <jwakely dot gcc at gmail dot com>
- To: "Mateusz Łoskot" <mateusz at loskot dot net>
- Cc: libstdc++ at gcc dot gnu dot org
- Date: Thu, 2 Mar 2006 10:12:47 +0000
- Subject: Re: Strange behaviour of strchr in C++
- References: <44038EA2.1050301@loskot.net> <20060228000658.GE2604@synopsys.com> <4403968E.906@loskot.net> <44039858.208@suse.de> <44039F06.80009@loskot.net> <20060228005632.GG2604@synopsys.com> <4403A467.6060707@loskot.net>
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