I was reading a C++ template example, and part of the template signature confused me.
Am I reading this correctly:
const T* const foo;
Is foo
a const*
to a const T
?
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.
int const* is pointer to constant integer This means that the variable being declared is a pointer, pointing to a constant integer. Effectively, this implies that the pointer is pointing to a value that shouldn't be changed.
A constant pointer in C cannot change the address of the variable to which it is pointing, i.e., the address will remain constant. Therefore, we can say that if a constant pointer is pointing to some variable, then it cannot point to any other variable.
Const means simply, as you described, that the value is read-only. constant expression, on the other hand, means the value is known compile time and is a compile-time constant.
Yes, it's a constant pointer to a constant T
. I.e., you can neither modify the pointer, nor the thing it points to.
const T*
would only forbid you to modify anything the pointer points to, but it allows you (within the bounds of the language) to inspect the value at *(foo+1)
and *(foo-1)
. Use this form when you're passing pointers to immutable arrays (such as a C string you're only supposed to read).
T * const
would mean you can modify the T
value pointed to by foo
, but you cannot modify the pointer itself; so you can't say foo++; (*foo)++
because the first statement would increment (modify) the pointer.
T *
would give you full freedom: you get a pointer into an array, and you can inspect and modify any member of that array.
This is a const pointer-to-const T. So if T was an int, then array is a pointer to an int that is const in two ways:
pointer-to-const: the value that the pointer is pointing to cannot be changed (or pointing to const int) const pointer: the memory address stored in the pointer cannot change
This is also the same as T const * const array
See wiki on const correctness.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With