Sign in to follow this  
mattnenterprise

arrays

Recommended Posts

I have a Question about an array.I have code that looks like this. int ArSize = 12; const const char * months[ArSize] = { "January","February","March", "April","May","June", "July","August","September", "October","November","December" }; and it won't compile but when I do this It will work int ArSize = 12; const char * months[12] = { "January","February","March", "April","May","June", "July","August","September", "October","November","December" }; I was wondering why one works and not the other

Share this post


Link to post
Share on other sites
In C++, the size of an array must be a compile-time constant. Since ArSize is not a constant at all in the first example, it cannot be used as an array size.

Note that you can use:

template <typename T, size_t N> size_t array_size(const T (&arr)[N]) 
{ return N; }

const char *months[] = { /* ... */ }
size_t arSize = array_size(months);

Share this post


Link to post
Share on other sites
Your first example won't compile because your compiler won't know what to do about that double const, but here's what I get when I type in your code withonly one: ISO C++ forbids variable-size array.

What this means is, C++ can't handle arrays of variable size; it must know what the size of an array is at compile time. It needs to know how much space to use, even if it's on the stack.

BTW: If by the double const, you meant cont array of const chars, don't worry about it, they are because you defined them with literals. Besides, the syntax for that would be const char* const.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this