domlao
domlao

Reputation: 16029

Initialize a static const empty array

Is it possible to initialize a static const empty array, please see below code,

//CFoo.h
class CFoo
{
 public:
   CFoo();
   ~CFoo();

 public:
    static const int arr[];

};

//CFoo.cpp
const int arr[] = {0,1,2};

CFoo::CFoo(){}
CFoo::~CFoo(){}

EDIT:

It seems the code is valid, and for followup question, why I can't sizeof the static const array, like,

sizeof( CFoo::arr );

Is there any way I can sizeof CFoo::arr?

Thanks.

Upvotes: 0

Views: 1127

Answers (3)

Tony Delroy
Tony Delroy

Reputation: 106244

sizeof is evaluated at compile time, not link time, so no - you can't leave it unspecified in the header yet have it evaluated before the definition.

Upvotes: 3

James McNellis
James McNellis

Reputation: 355357

Yes; you need to qualify the name of the array:

const int CFoo::arr[] = {0,1,2};

The type of CFoo::arr is incomplete until the definition, so you are limited in how you can use it. For example, you cannot use it as the argument of sizeof. If you complete the declaration, then there's no problem:

struct CFoo {
    static const int arr[3];
};

Note, however, that this has maintainability issues because the size is specified in two separate places, and you likely won't get an error if there are fewer initializer values than the declared size of the array.

Upvotes: 5

fabmilo
fabmilo

Reputation: 48330

Yes.

const int CFoo:arr[] = {0,1,2};

Upvotes: 3

Related Questions