A reason for this problem (which is even harder to detect than the issue with char* str = "some string"
- which others have explained) is when you are using constexpr
.
constexpr char* str = "some string";
It seems that it would behave similar to const char* str
, and so would not cause a warning, as it occurs before char*
, but it instead behaves as char* const str
.
Details
Constant pointer, and pointer to a constant. The difference between const char* str
, and char* const str
can be explained as follows.
const char* str
: Declare str to be a pointer to a const char. This means that the data to which this pointer is pointing to it constant. The pointer can be modified, but any attempt to modify the data would throw a compilation error.
str++ ;
: VALID. We are modifying the pointer, and not the data being pointed to.
*str = 'a';
: INVALID. We are trying to modify the data being pointed to.
char* const str
: Declare str to be a const pointer to char. This means that point is now constant, but the data being pointed too is not. The pointer cannot be modified but we can modify the data using the pointer.
str++ ;
: INVALID. We are trying to modify the pointer variable, which is a constant.
*str = 'a';
: VALID. We are trying to modify the data being pointed to. In our case this will not cause a compilation error, but will cause a runtime error, as the string will most probably will go into a read only section of the compiled binary. This statement would make sense if we had dynamically allocated memory, eg. char* const str = new char[5];
.
const char* const str
: Declare str to be a const pointer to a const char. In this case we can neither modify the pointer, nor the data being pointed to.
str++ ;
: INVALID. We are trying to modify the pointer variable, which is a constant.
*str = 'a';
: INVALID. We are trying to modify the data pointed by this pointer, which is also constant.
In my case the issue was that I was expecting constexpr char* str
to behave as const char* str
, and not char* const str
, since visually it seems closer to the former.
Also, the warning generated for constexpr char* str = "some string"
is slightly different from char* str = "some string"
.
- Compiler warning for
constexpr char* str = "some string"
: ISO C++11 does not allow conversion from string literal to 'char *const'
- Compiler warning for
char* str = "some string"
: ISO C++11 does not allow conversion from string literal to 'char *'
.
Tip
You can use C gibberish ↔ English converter to convert C
declarations to easily understandable English statements, and vice versa. This is a C
only tool, and thus wont support things (like constexpr) which are exclusive to C++
.