Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the meaning of multiple const qualifiers?

Code:

const char* const* const* foo(int bar);

I've seen double consts before which prevent the modification of the pointer too. First time i've seen triple const in my life. Wondering what its use is.

like image 215
Learath2 Avatar asked Apr 13 '14 13:04

Learath2


People also ask

What is constant qualifier?

The const qualifier explicitly declares a data object as something that cannot be changed. Its value is set at initialization. You cannot use const data objects in expressions requiring a modifiable lvalue. For example, a const data object cannot appear on the lefthand side of an assignment statement.

Where may a const type qualifier appear?

In a function declaration, the keyword const may appear inside the square brackets that are used to declare an array type of a function parameter. It qualifies the pointer type to which the array type is transformed.

Is const qualified at the top level?

Whenever const appears immediately before or after the type of the identifier, that is considered a top-level qualifier.

What does const mean in C?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.


2 Answers

In your example all but the top level of indirection all const qualified.

const char            /* const qualified base level */
    *const            /* const qualified level 1 */
    *const            /* const qualified level 2 */
    *                 /* regular level 3 */
    foo(int bar);

foo is a function that accepts an int argument and returns a regular pointer.
The pointer it returns points to a const qualified pointer
which, in turn, points to another const qualified pointer
which points to const qualified char

like image 131
pmg Avatar answered Oct 18 '22 18:10

pmg


If you have a multilevel pointer, you have several pointer variables. Example:

char*** foo;

is accessed like this:

| foo | pointer1 | pointer2 | string |
   |    ^     |    ^     |    ^
    \___/      \___/      \___/

You can qualify each of the four locations in memory as being const, as in the declaration

const char *const *const *const foo;

However, best avoid becoming a three star programmer.

like image 42
cmaster - reinstate monica Avatar answered Oct 18 '22 18:10

cmaster - reinstate monica