Is const char * string or pointer

I thought const char * is a mutable pointer to an immutable string.

However, when I do this,

#include <iostream>
using namespace std;

const char *name1 = "Alex";

int main() 
{
   name1 = "John";
   cout << name1 << endl;
}

he just prints John and shows no problems. I wonder why the program treats name1 as a string and makes it mutable?

+4
source share
5 answers

I wonder why the program treats name1 as a string and makes it mutable?

This is not so, you just assigned a new address to the pointer (address "John"). You yourself said " mutable pointer to immutable string". You changed the pointer, and if you tried to actually modify the pointer, the type system would prevent you from doing this (because of the const specifier).

+5

"", , "".

+3
  • - .
  • "" 1.
  • cout , char *, .

+2

/ ( ): ...

const char *name1 = "Alex";

int main() 
{
    name1[0] = 'J';
    name1[1] = 'o';
    name1[2] = 'h';
    name1[3] = 'n';
    std::cout << name1 << std::endl;
    return 0;
}

. , ! const_cast<char>(name[x]) = y; . , , , , undefined !

, const const ( , - const ly ).

+2

, 1 ?

const *. name1, char * const. . const int *, const int * const int const *?

, const , , .

0

Source: https://habr.com/ru/post/1696192/


All Articles