array declaration, is this legal?

B

b83503104

Hi,

I wonder if this is a legal array declaration?

const int size = 5;
double array[size];

Or should I use "new"?

Thanks.
 
H

Howard

Hi,

I wonder if this is a legal array declaration?

const int size = 5;
double array[size];

Yes, it's legal, because it uses a const int initialized by a constant
expression. This allows the compielr to treat it as a compile-time
constant, just as if you'd simply used the constant expression 5 directly in
the array declaration.

-Howard
 
G

Greg

Hi,

I wonder if this is a legal array declaration?

const int size = 5;
double array[size];

Or should I use "new"?

Thanks.

You should use the constant expression for a statically-sized array
since the number of bytes needed is known at compile time. Using new in
this situation incurs unnecessary overhead at runtime; worse, it
imposes on the program a requirement to call delete on the array, which
if neglected, will cause memory to leak.

In general, use new to allocate arrays that are either too large to be
allocated on the stack or whose size is not known until runtime.

Greg
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,439
Members
44,829
Latest member
PIXThurman

Latest Threads

Top