Compilation of given code sample with gcc/g++ succeeds. There is no error for strchr
call, which obviously assignes const char *
to char *
.
I've found strchr
is declared as char * strchr(const char *, int)
on two different sources pubs.opengroup.org and cplusplus.com
If strchr
is implemented as to cast away constness, then why's that so?
If goal was to provide function which works both on char *
and const char *
strings - it could have been implemented using two different function names.
Can you give more thorough explanation on this.
#include <string.h>
int main () {
const char *str = "Sample string";
char * ptr;
//ptr = str; // Error: discards const qualifier - both on gcc and g++
pch = strchr(str,'S'); // Succeeds in assigning <const char *> to <char *>
*pch = '4'; // Runtime error: segmentation fault
return 0;
}
Tried it on Win7 using MSYS2/mingw-w64 gcc_v5.3.0 and TDM-gcc32 v5.1.0 .