+ 1
Confusion on const char*
Hi We can have const int* and int* const.. I am aware about these two along with int const * as well as const int * const. I have just captured these into sample code below: Question is related to const char* It is neither as per const int* or int* const Am I missing something or const char* is totally different? What is constant in this declaration? https://code.sololearn.com/c9ig21YSVy5e/?ref=app
4 Respostas
+ 3
Well
------
const int* p1 = &a;
++a;//works as a is not const
p1 = &b;//works as pointer is not const
++p1;// works and p1 is not pointing to b now but points to some next memory location
//++(*p1);//not work as const int means int value is const and p1 cant modify pointed value
------
------
const char* p = "Hello\n";
p = "World\n"; //works as pointer is not const
++p; // works and *p* is not pointing to 'W' now but points to some next memory location ('o')
cout << *p << "\n";
//++(*p); //not work as const char means char value is const and *p* cant modify pointed value
------
Question is why you think *p* is not behaving like *p1* ?
+ 2
I'm not quite sure what you mean?
const char* functions the same as const int*.
In this case, 'char*' or 'char* const' works a little different than 'int*' or 'int* const' only because the pointed-to string is stored in read only memory, so you can't assign it a different character. If that is what you mean.
+ 2
char* name = "blah blah"; <= this will compile as normal but if you try to modify it at run time, your prog will fail.
const char* name = "blah blah" ; <= this will NOT even compile if your code tries to modify it.
+ 1
Thanks rodwynnejones , Dennis and Arsenic
I was confused about what is const in case of const char*
Char* is nothing but string kind of and hence "hello" string is constant.. so can't modify the same like Hello or Dello
In short this we should define as const char* as what we assigned initially is in code or constant section