Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialising specific elements of a static const array in C++

I have some C that I need to convert to C++.

It does something like this:

enum
{
   ELEM0,
   ELEM1,
   ELEM2,
   ELEM3,
   ELEM4,
   MAX_ELEMS
} 

#define LEN 16

static const char lut[MAX_ELEMS][LEN] =
{
    [ELEM2] = "Two",
    [ELEM3] = "Three",
    [ELEM1] = "One",
    [ELEM4] = "Four",
    [ELEM0] = "Zero"
}

In practice I have hundreds of elements without any order in the array. I need to guarantee that the entry in the array ties up the enumeration to the appropriate text.

Is it possible to initialise an array using positional parameters like this in -std=gnu++11?

like image 991
Joe Avatar asked Oct 29 '13 15:10

Joe


People also ask

Can you modify a const array in C?

You can't. The const keyword is used to create a read only variable. Once initialised, the value of the variable cannot be changed but can be used just like any other variable. That means, a const qualified variable must not be assigned to in any way during the run of a program.

Can static members be const?

A static data member can be of any type except for void or void qualified with const or volatile. You cannot declare a static data member as mutable.

What are the different ways of initializing array in C?

There are two ways to specify initializers for arrays: With C89-style initializers, array elements must be initialized in subscript order. Using designated initializers, which allow you to specify the values of the subscript elements to be initialized, array elements can be initialized in any order.


1 Answers

No. Per gcc documentation, Designated Initializers do not exists in GNU C++.

In ISO C99 you can give the elements in any order, specifying the array indices or structure field names they apply to, and GNU C allows this as an extension in C89 mode as well. This extension is not implemented in GNU C++.

Doesn't this solve you problem (although it's run-time):

static const std::map<int, std::string> lut =
{
    std::make_pair(ELEM2, "Two"),
    std::make_pair(ELEM3, "Three"),
    std::make_pair(ELEM1, "One"),
};
like image 106
masoud Avatar answered Oct 20 '22 01:10

masoud