I've been working on a project with MinGW on Windows for a while now, and I am now trying to compile it on Mac (using GCC). I am using Qt, but that doesn't have much to do with the problem.
Why is GCC being so formal, and making me cast everything? It's ridiculous how I have to go through and cast everything that doesn't match.
For example, it would throw the error:
main.cpp: error: invalid conversion from 'const char*' to 'char*'
With this code:
const char *a = "a";
char *b = a;
Are there any flags I could pass to the GCC compiler or any preprocessor directives to tell it to ignore these? Thanks.
Edit: Let me rephrase. Why does that work on MinGW but not GCC, and could I get it to work on GCC?
Edit 2: MinGW - https://i.sstatic.net/xFuO7.png
It's not that gcc is pedantic. const char* is a pointer to const char, which is a very different type from char*, which points to char. For the later you can modify the contents of the pointer, for the former you can't. Allowing this conversion to be implicit would invite seriuos bugs, since it would be trivial to modify the contents of a by using a non const pointer, even though the contents are supposed not to be modifiable.
Theoretically you can cast the constness away:
char* b = const_cast<char*>(a);
This tells the compiler that you know that what you are doing is unsafe, but you are taking full blame if something terrible happens (you try to modify the data of a const char*), since you explicitly told it that ignoring the constness is fine at that position. Something like that should be done sparsely and only after verifying that it is ok.
Looking it up gcc and mingw actually accept the implicit cast when compiling with -fpermissive (which downgrades it to a warning). However using such unsafe features is a very bad idea, so my advice is to stay as far as possible away from such evil temptations. Instead of lowering the error threshhold I'd rather suggest options like -Wall, -Wextra and maybe even -pedantic and -Werror to make the compiler as picky as possible. Doing so may be a a pain when programming, but can easily spare you hours of debugging (with a no warning policy or -Werror of course).
Not directly related to your question, but since you are using c++: Why do you need char* when you could use std::string?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With