Topic: Array declaration question


Author: dave.lowe@gmail.com
Date: Wed, 8 Dec 2004 14:20:19 CST
Raw View
I've been very use to the requirement of using a constant expression
for array size during array declaration.

I was just told that the C++ standard allows the following:

..
void foo(int n) {
int myArray[n];
for (int i = 0; i < n; myArray[i++] = 0);
}

int main() {
int arraySize = 1000;
foo(arraySize);
return 0;
}

Now, this *seems* to be just plain wrong; however, some c++ compilers
accept it, while some don't.  I thought the standard stated you must
use a constant expression.

Can anyone please tell me what the actual standard says is legal
(regardless of how compilers implement it)?

Thanks!

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: alfps@start.no (Alf P. Steinbach)
Date: Wed, 8 Dec 2004 20:47:44 GMT
Raw View
* dave.lowe@gmail.com:
>
> I was just told that the C++ standard allows the following:
>
> ..
> void foo(int n) {
> int myArray[n];
> for (int i = 0; i < n; myArray[i++] = 0);
> }

That's incorrect.

It is allowed in C99 (C is not C++, and C99 is not previous
versions of C).


> Can anyone please tell me what the actual standard says is legal
> (regardless of how compilers implement it)?

n must be a compile-time integral constant, except when you allocate
the array dynamically.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: ark@acm.org ("Andrew Koenig")
Date: Wed, 8 Dec 2004 22:26:32 GMT
Raw View
<dave.lowe@gmail.com> wrote in message
news:1102531235.242333.57250@f14g2000cwb.googlegroups.com...

> I was just told that the C++ standard allows the following:

> void foo(int n) {
> int myArray[n];
> for (int i = 0; i < n; myArray[i++] = 0);
> }

It doesn't.  Whoever told you that is mistaken.

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]