Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a static const array of const char*

Tags:

c++

I tried the following line:

static const const char* values[]; 

But I get the following warning on VC++ warning C4114:

same type qualifier used more than once.

What is the correct declaration? The goal is to create an immutable array of c strings.

like image 213
Tommy Avatar asked Jun 12 '12 14:06

Tommy


People also ask

What is a static const char * in C++?

const char* is a pointer to a constant char, meaning the char in question can't be modified. char* const is a constant pointer to a char, meaning the char can be modified, but the pointer can not (e.g. you can't make it point somewhere else).

What does const char * const mean?

In C programming language, *p represents the value stored in a pointer and p represents the address of the value, is referred as a pointer. const char* and char const* says that the pointer can point to a constant char and value of char pointed by this pointer cannot be changed.

What is const char * str?

The const char *Str tells the compiler that the DATA the pointer points too is const . This means, Str can be changed within Func, but *Str cannot. As a copy of the pointer is passed to Func, any changes made to Str are not seen by main....

Can an array be const?

Arrays are Not Constants It does NOT define a constant array. It defines a constant reference to an array. Because of this, we can still change the elements of a constant array.


2 Answers

You wrote const const instead of static const char* const values[]; (where you define the pointer and the underlying values as const)

Also, you need to initialize it:

static const char* const values[] = {"string one", "string two"};

like image 131
Mesop Avatar answered Oct 19 '22 20:10

Mesop


Try

static const char* const values[];

The idea is to put the two consts on either side of *: the left belongs to char (constant character), the right belongs to char* (constant pointer-to-character)

like image 5
Attila Avatar answered Oct 19 '22 19:10

Attila