13

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.

0

2 Answers 2

26

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"};

Sign up to request clarification or add additional context in comments.

4 Comments

Do I understand correctly, the first const is for the string and the second for the array?
To clarify the keyword const: A const is always related to the "item" left to it. The exception of this is, when const is the first word in the expression, then it relates to the item right to it. So to be super-correct, one would define the string as static char const * const values[], which can be read right to left: values is an array of const pointers to const chars and all of this is static.
@AquilaRapax There are actually quite a few reasons for writing the definition the way you did. Typedefs are very confusing otherwise: typedef const char* CPtr; const CPtr var; doesn't mean what it might seem to mean, where as typedef char const* CPtr; CPtr const var; is much clearer.
@JamesKanze: The priority of [ ] is greater than *, and since * is added from the right, so does const. Never mind, I'm answering the 9-year-ago-you.
5

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.