array declaration, is this legal?

Discussion in 'C++' started by b83503104@yahoo.com, Jul 12, 2005.

  1. Guest

    Hi,

    I wonder if this is a legal array declaration?

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

    Or should I use "new"?

    Thanks.
    , Jul 12, 2005
    #1
    1. Advertising

  2. wrote:
    > I wonder if this is a legal array declaration?
    >
    > const int size = 5;
    > double array[size];


    Yes, it is. 'size' is a compile-time constant expression.

    > Or should I use "new"?


    Up to you.

    V
    Victor Bazarov, Jul 12, 2005
    #2
    1. Advertising

  3. Howard Guest

    <> wrote in message
    news:...
    > 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
    Howard, Jul 12, 2005
    #3
  4. Greg Guest

    wrote:
    > 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
    Greg, Jul 14, 2005
    #4
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Noah
    Replies:
    5
    Views:
    947
  2. Joost Kraaijeveld

    Is this forward declaration legal C++?

    Joost Kraaijeveld, Jun 28, 2004, in forum: C++
    Replies:
    7
    Views:
    453
    Sharad Kala
    Jun 29, 2004
  3. Carramba

    is this legal declaration/not correct output

    Carramba, May 16, 2007, in forum: C Programming
    Replies:
    12
    Views:
    554
    David Thompson
    Jul 1, 2007
  4. Replies:
    2
    Views:
    345
  5. Universe
    Replies:
    6
    Views:
    304
    Universe
    Mar 26, 2011
Loading...

Share This Page