Gerald Maus
Gerald Maus

Reputation: 1

Declare array with declared constant

I'm trying to do something like this:

const int array_size = 5;
string stuff[array_size];

My compiler won't let me compile this, even though array_size is a constant. Is there a way to do this without dealing with dynamic arrays?

Edit: "error C2057: expected constant expression"

Upvotes: 0

Views: 270

Answers (5)

sbabbi
sbabbi

Reputation: 11181

Only thing I can think of is that you defined another array_size variable in your code, which is not a compile time constant and hides the original array_size.

Upvotes: 0

jxh
jxh

Reputation: 70382

I have answered this question assuming you are either coding in C or C++. If you are using a different language, this answer doesn't apply. However, you should update your question with the language you are trying to use.

Consider the following program:

int main () {
    const int size = 5;
    int x[size];
    return 0;
}

This will compile in both C++ and C.99, but not C.89. In C.99, variable length arrays were introduced, and so locally scoped arrays can take on a size specified by a variable. However, arrays at file scope in C.99 cannot take a variable size parameter, and in C.89, all array definitions have to have a non variable size.

If you are using C.89, or defining a file scope array in C.99, you can use an enum to name your constant value. The enum can then be used to size the array definition. This is not necessary for C++ however, which allows a const integer type initialized by a literal to be used to size an array declaration.

enum { size = 5 };
int x[size];
int main () { return 0; }

Upvotes: 5

Mahesh
Mahesh

Reputation: 34625

array_size is not treated as a compile time constant. Constness added just makes sure that programmer can not modify it. If tried to modify accidentally, compiler will bring to your attention.

Size of an array needs to be a compile constant. Seems like your compiler is not supporting Variable Length Array. You can #define the size of the array instead which is treated as a constant expression.

Upvotes: -1

pzaenger
pzaenger

Reputation: 11973

You can use e.g. a vector or the new keyword to allocate memory dynamically, because declared arrays can not have runtime sizes.

Upvotes: 0

abelenky
abelenky

Reputation: 64682

#define array_size 5
string stuff[array_size];

Upvotes: 0

Related Questions