0
const char numm = 11;   
typedef char* pstring;
const pstring cstr = &numm; //Error
     

I learned this from C++ Primer, but it didn't quite clarify it for me. Here is a code example.

  • https://isocpp.org/wiki/faq/const-correctness#const-ptr-vs-ptr-const – Ghasem Ramezani Sep 11 '21 at 17:11
  • The `const` is applied to the type. You are applying it to the `pstring`, which is the same as if you had done: `char * const cstr = &numm;` ... and that's not what you wanted, you wanted `char const * cstr = &numm;` – Eljay Sep 11 '21 at 17:14
  • 1
    Try reading your code aloud (to force you to hear what you wrote instead of what you meant to write)? You've declared `cstr` to be a `const pstring`, a `pstring` that cannot be changed. What is a `pstring`? It's a `char*`. So the type of `cstr` is a pointer that cannot be changed. – JaMiT Sep 11 '21 at 17:15
  • `pstring` is a `char*`. If you now declare a `const pstring` you get a constant (char **pointer**). I added the braces to indicate the "ordering" of "operation". On the other hand, `const char *` is declaring a pointer to a constant char. – Sebastian Hoffmann Sep 11 '21 at 17:15
  • The main missunderstanding here is that `typedef` is not simply text substitution. – Sebastian Hoffmann Sep 11 '21 at 17:16
  • The target is for C, but the described behavior in the target question is the same for both languages, and the answer applies to both languages as well. – cigien Sep 11 '21 at 17:16
  • @SebastianHoffmann So in basic terms of speaking, declaring a const pstring I'm basically saying make char * const right? –  Sep 11 '21 at 17:18
  • @Gamerguy123lo exactly – Sebastian Hoffmann Sep 11 '21 at 17:28

0 Answers0