Write your question here.
Hello,
"from a book" this small program does not compile.
I get this error: ISO C++ forbids converting a string constant to ‘char*’
thanks in advance,
Michel Chassey
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
int main()
{
char * adr;
adr = "have a good day";
while( *adr )
{
std::cout << *adr;
adr++;
}
} // end of main
hello there:
yea the string "have a good day"; is of type const char* not type char*
so your code should look like this
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
int main()
{
constchar * adr;
adr = "have a good day";
while( *adr )
{
std::cout << *adr;
adr++;
}
} // end of main
why the error?
const char* is read-only, meaning you can't modify what is being pointed to, but then you attempt to assign it to a normal char*, which means you *can* modify it... your compiler will never let that happen.
> "from a book" this small program does not compile.
> I get this error: ISO C++ forbids converting a string constant to ‘char*’
The book is somewhat dated; the program was made ill-formed by a change to the standard in 2011.
From the C++11 standard (Annex C Compatibility):
Change: String literals made const
The type of a string literal is changed from “array of char” to “array of const char.” ...
The type of a wide string literal is changed from “array of wchar_t” to “array of const wchar_t.”
... Effect on original feature: Change to semantics of well-defined feature. Difficulty of converting: Syntactic transformation. The fix is to add a cast
... How widely used: Programs that have a legitimate reason to treat string literals as pointers to potentially modifiable memory are probably rare.
Thanks for the speedy answers.
I am reading a french book titled "Programmer en Langage C++" where it says somewhere :
"Achevé d'imprimer le 29 septembre 2017"
This is on page 173.
Topical answer from JLBorges :
From the C++11 standard (Annex C Compatibility):
Change: String literals made const
The type of a string literal is changed from “array of char” to “array of const char.” ...
The type of a wide string literal is changed from “array of wchar_t” to “array of const wchar_t.”
M. JLBorges would you be so kind as to name your reference material as it would most helpful.
I can't understand why a manual published in 2017 would miss the C++11 standard.