Bento Bento - 2 months ago 17
C Question

C/C++ convention for pointers and `const`

I have read this (Pasted below as well) on Wikipedia:


Following usual C convention for declarations, declaration follows use, and the * in a pointer is written on the pointer, indicating dereferencing. For example, in the declaration int *ptr, the dereferenced form *ptr is an int, while the reference form ptr is a pointer to an int. Thus const modifies the name to its right. The C++ convention is instead to associate the * with the type, as in int* ptr, and read the const as modifying the type to the left. int const * ptrToConst can thus be read as "*ptrToConst is a int const" (the value is constant), or "ptrToConst is a int const *" (the pointer is a pointer to a constant integer).


I really am not able to get a satisfying interpretation:


  • In which sense does it modify?

  • What is intended with name vs type (see the above link)?

  • And why should it be on the right side of
    const
    ?


Answer

In which sense does it modify?

Modifies in the sense that it makes it constant, meaning it can't be modifed (assigned to, or passed to a function which might modify it).

What is intended with name vs type (see the above link)?

Name means the word written in the source code here, I think.

And why should it be on the right side of const?

"Modifies name to its right" means, by example:

const char * str, here const modifies char, in other words the characters are constant, you can't modify them. You can make str point to a new char, but you still can't modify it either (at least not through str). *str = 'a'; is compiler error, str = "foo"; is ok.

char * const str, here const modifies str, in other words the value of str can't be modified. It points to some char, and you can modify that char through str, but you can't make str to point to another char. *str = 'a'; is now ok, str = "foo"; is error.