Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double const declaration

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.

like image 826
SyBer Avatar asked Jan 28 '10 16:01

SyBer


People also ask

What is a const double?

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; )

What is const declaration?

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.

What does const do in function declaration C++?

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.

How do you declare a constant variable in C++?

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.


2 Answers

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
like image 105
wich Avatar answered Oct 01 '22 01:10

wich


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 definition
  • T 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
like image 22
just somebody Avatar answered Oct 01 '22 00:10

just somebody