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

4
  • Do I understand correctly, the first const is for the string and the second for the array?
    – Tommy
    Commented Jun 12, 2012 at 14:19
  • 10
    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. Commented Jun 12, 2012 at 14:28
  • @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. Commented Jun 12, 2012 at 15:03
  • 1
    @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. Commented Feb 18, 2021 at 15:55
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)

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.