I often see the following function declaration:
some_func(const unsigned char * const buffer)
{
}
Any idea why the const is repeated before the pointer name?
Thanks.
This can be used in several ways. Examples: Declaring a variable to be const means that its value cannot change; therefore it must be given a value in its declaration: const double TEMP = 98.6; // TEMP is a const double. ( Equivalent: double const TEMP = 98.6; )
A constant holds a value that does not change. A constant declaration specifies the name, data type, and value of the constant and allocates storage for it. The declaration can also impose the NOT NULL constraint.
Const member functions in C++The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided. A const member function can be called by any type of object. Non-const functions can be called by non-const objects only.
Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.
The first const
says that the data pointed to is constant and may not be changed whereas the second const
says that the pointer itself may not be changed:
char my_char = 'z';
const char* a = &my_char;
char* const b = &my_char;
const char* const c = &my_char;
a = &other_char; //fine
*a = 'c'; //error
b = &other_char; //error
*b = 'c'; //fine
c = &other_char; //error
*c = 'c'; //error
type declarations should(?) be read RTL. const
modifies the thing on its left, but the rule is complicated by the fact that you can write both const T
and T const
(they mean the same thing).
T * const
is a constant pointer to mutable T
T & const
would be constant reference to mutable T, except references are constant by definitionT const *
is a mutable pointer to constant T
T const &
is a reference to constant T
T const * const
is constant pointer to constant T
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