0

I read this but I did not really get what I searched for.

Why can I do this:

char duder[] = "duder";

When I cannot do this:

const char dusder[] = "dusder";
char nondusder[] = dusder;

So AFAIK the literals create constant unnamed array and why can't you then initialize an array to another array yourself if that is technically what is happening when doing char duder[] = "duder";?

Also, how can duder modify the string literal if it is constant?

If (even though I did search for this but did not find the answer to my question) there is a source that answers my questions, I would of course appreciate a link just as much as an answer :)

Community
  • 1
  • 1
  • 3
    You shouldn't read the C reference page, but the C++ reference page instead: http://en.cppreference.com/w/cpp/language/string_literal – UnholySheep Jun 29 '17 at 06:46
  • @UnholySheep thanks for the link. But it doesn't look like that it answers any of my questions, or am I blind? –  Jun 29 '17 at 06:52
  • 1
    It answers the question *"how can `duder` modify the string literal if it is constant?"*: *"If an array is initialized like `char str[] = "foo";`, `str` will contain a copy of the string `"foo"`."* - Note that this is not the case in C - there modifying a string literal always leads to *undefined behavior* – UnholySheep Jun 29 '17 at 06:53
  • @UnholySheep: You're mixing up two types here. `char duder[]` is _initialized_ with a string literal. It's a copy. It can't modify the string literal, because it doesn't point to the string literal. Now, it it was `char* duder = "duder";`, you'd have a point. – MSalters Jun 29 '17 at 06:59
  • @MSalters please tell me how the linked question answers this? Like it does not explain why an array can be initialized to a string literal when that string literal technically is another array= –  Jun 29 '17 at 07:06
  • @NeiLee: As the first answer points out, that's just how the language is defined. It's inherited from C. As C++ normally uses `std::string`, fixing this inconsistency was never a priority. – MSalters Jun 29 '17 at 07:09

0 Answers0