Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declare a array of const ints in C++

I have a class and I want to have some bit masks with values 0,1,3,7,15,...

So essentially i want to declare an array of constant int's such as:

class A{

const int masks[] = {0,1,3,5,7,....}

}

but the compiler will always complain.

I tried:

static const int masks[] = {0,1...}

static const int masks[9]; // then initializing inside the constructor

Any idea on how this can be done?

Thanks!

like image 928
Juan Besa Avatar asked May 30 '09 01:05

Juan Besa


People also ask

How do you declare an array in C?

To create an array, define the data type (like int ) and specify the name of the array followed by square brackets []. To insert values to it, use a comma-separated list, inside curly braces: int myNumbers[] = {25, 50, 75, 100}; We have now created a variable that holds an array of four integers.

What is constant array in C?

it's a constant array of integers i.e. the address which z points to is always constant and can never change, but the elements of z can change.

Can I #define an array in C?

In the latest version of C, you can either declare an array by simply specifying the size at the time of the declaration or you can provide a user-specified size. The following syntax can be used to declare an array simply by specifying its size. // declare an array by specifying size in [].

Can we declare array as constant?

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

class A {
    static const int masks[];
};

const int A::masks[] = { 1, 2, 3, 4, ... };

You may want to fixate the array within the class definition already, but you don't have to. The array will have a complete type at the point of definition (which is to keep within the .cpp file, not in the header) where it can deduce the size from the initializer.

like image 53
Johannes Schaub - litb Avatar answered Sep 30 '22 08:09

Johannes Schaub - litb


// in the .h file
class A {
  static int const masks[];
};

// in the .cpp file
int const A::masks[] = {0,1,3,5,7};
like image 29
Mr Fooz Avatar answered Sep 30 '22 06:09

Mr Fooz