0
char c[]="opop";
c[2]='k';

But it should give a bus error,why does it work?

Chuck Norris
  • 15,207
  • 15
  • 92
  • 123
Rachit
  • 501
  • 1
  • 4
  • 4
  • 3
    Even if you were actually modifying a string literal (which you aren't), a premise of "Why does invoking undefined behavior work here?" is flawed. Undefined behavior means that *anything* could happen (including some definition of "working"). – jamesdlin May 03 '12 at 06:07
  • I thought the title was saying `std::string` is immutable, which, of course, it's not. – Peter Wood May 03 '12 at 06:45

1 Answers1

7

What you have is an array, not an string literal. It is perfectly valid code.

char *c="opop";
c[2]='k';

Would cause an Undefined Behavior and most likely a crash.

Good Read:
What is the difference between char a[] = "string"; and char *p = "string";

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • 1
    I'd like to add a comment that Turbo C++ is old, and that string literals (defined by char * = "opop") used to be writeable for backwards compatibility. GCC still has a -wwriteable-strings (I believe) flag to allow this. – std''OrgnlDave May 03 '12 at 05:53
  • @std''OrgnlDave: The link in the answer to one of my old answer explains this much more in detail with standardese quotes. – Alok Save May 03 '12 at 05:55
  • I haven't used C++ for 8 years. Is this immutability a "new" feature of the language? Also, I always thought char c[] and char* c were synonyms? – Eduardo May 03 '12 at 05:55
  • @Eduardo read the link he posted. basically, char[] and char pointer are not the same data type; char[] can decay into char pointer, but it is not. short answer, char[] declares an array and initializes it, char pointer declares a pointer and points it to a string literal. – std''OrgnlDave May 03 '12 at 05:56
  • 1
    @Eduardo: An array and a pointer were never & still are not same in C/C++. It is one of the most widely spread misconception that they are synonymous, they are not! You should check out the link in the answer for a detailed description. – Alok Save May 03 '12 at 05:57
  • Very interesting link. I am trying to re-learn C++ these days and it is a very useful point to keep in mind. – Eduardo May 03 '12 at 05:57
  • @VJovic: Yes, in C++11, Not in C++03, C++03(§4.2/2) merely deprecates use of string literal without the `const` keyword. – Alok Save May 03 '12 at 06:22
  • @VJovic: The linked answer is mine and it aptly explains the semantics involved in greater detail.So I dont think that really justify's an downvote.Ofcourse, You don't need to justify any downvotes but Since that is the reasoning you present for the downvote its not really justified. – Alok Save May 03 '12 at 09:11
  • I didn't downvote (I could only prove by downvoting if you like). turbo c++ is an ancient compiler, so c++11 are not there (not sure if even c++03 are there). – BЈовић May 03 '12 at 12:04