char *str1 = "abcd"; str1[2]='x'; compiles?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

using namespace std;

int main()
{
	char *str1 = "abcd";
	const char *str2 = "efgh";

	str1[2] = 'x';
	//str2[2] = 'x';  compiler error, cannot change const

	return 0;
}


I am wondering about the compiler's decision to let the statement: str1[2]='x'; get by without error. Would it be fair to say that:

char *str1 = "abcd";
const char *str1 = "abcd";

are identical statements, since the string literal is a constant. In which case wouldn't it be adviseable for the compiler to generate a diagnostic for the assignment to str1 as it does for str2 ?

Or could there be a situation where it is possible, and legal, to change the string literal contents and therefore the const'ness of *str1 cannot be assumed?
Presumably not all platforms treat string literals as non-modifiable. There may even be compiler options to that effect.
All string literals are const char *, and modifying them is always illegal.
Line 7 has an implicit cast to char * which some compilers (such as VC++) allow. g++ gives a warning (something along the lines of "deprecated cast to 'char *'").

The type of a string literal is "array of the appropriate number of const characters".
[In other words, "string" is of type 'const char[7]'.]
[...]
A string literal can be assigned to a char *. This is allowed because in previous definitions of C and C++ , the type of a string literal was char *. Allowing the assignment of a string literal to a char * ensures that millions of lines of C and C++ remain valid. It is, however, an error to try to modify a string literal through such a pointer[.]

-Bjarne Stroustrup, The C++ Programming Language
Last edited on
ensures that millions of lines of C and C++ remain valid

Right! I remember reading that now.
Thanks Hammurabi, and esp. thanks helios for the quote from Stroustrup. That pretty much nails it on the head. I don't think I'm quite ready to argue about C++ standards with Mr. Stroustrup, I'll wait 'till I have a few more months C++ under my belt before I do that.
I'll wait 'till I have a few more months C++ under my belt before I do that.

Lmao try years mate! A quote from the man himself...

I (Bjarne Stroustrup) am the designer and original implementor of C++.
- http://www.research.att.com/~bs/C++.html
Topic archived. No new replies allowed.