views:

248

answers:

8

Hi.

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.

+1  A: 

This makes it a const pointer to a const value, rather than a mutable pointer to a const value or a const pointer to a mutable value.

Thom Smith
+3  A: 

It's a constant pointer to a constant unsigned char. You can't change the pointer nor the thing it points to.

Nikola Smiljanić
+2  A: 

const * unsigned char const buffer means that you cannot modify the pointer buffer nor the memory that buffer points to.

Kyle Lutz
+2  A: 

In a declaration like const * const T, the first const (before the *) means that what the pointer points at is const (i.e. it's a pointer to a const T). The const after the * means that the pointer itself is const (i.e. can't be modified to point at anything else).

Jerry Coffin
+1  A: 

A couple of articles to help you understand const correctness in C++:

ceretullis
+10  A: 

The first const says that the data pointed to is constant and may not be changed, the second 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
wich
+1 But might I suggest adding examples demonstrating that const pointers may not be reassigned. (i.e., `char* const x = NULL; x = `)
Eric
@Eric I believe I already included that `b = //error`
wich
@wich I believe I need to pay more attention :) My apologies
Eric
+2  A: 

assuming const unsigned char * const

Everyone is correct that its a const pointer to a const unsigned char.

C++ types read mostly right to left unless there are any modifiers on the far left then these read left to right.

jk
+3  A: 

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
just somebody
Thanks, the RTL reading advice is useful for such feature cases.
SyBer