My book says this shouldnt compile, but it does?

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

int main(){
    int i;
    std::cin>>i;
    int p[i];
    for(int j=i-1;j>=0;j--){
        p[j] = j*2;
        std::cout<<p[j]<<"\n";
    }
}

every book i read says i cant do this, but i can? why am i able to do this? and if im able to do this whats wrong with doing it?
That code can not be compiled.

You can only set the size of an array with a constant, unless you allocate it yourself.
ive compiled and run it already.
Some compiler allow unstandard behaviours but you shouldn't use these features, they aren't portable
That's GCC, right? Try adding the compiler option -pedantic.
Would it be proper to do something more like:
int *p = new int[i]
or is that nonstandard too?

EDIT: -pedantic is SO helpful! I have it permanantly set <_<
Last edited on
That's the only standard way of creating dynamically-sized arrays in C++ (other than malloc(), but you shouldn't use that).
Actually, that code should compile under C99 (they implemented VLAs in there).
if i compile it, it works. very strange
Yes, but C++ is derived from C89.
Also, C doesn't have iostream. :-)
closed account (S6k9GNh0)
I ran into this the other day as well. I noticed it would never compile on VC++ but it will on GCC and I couldn't figure out if VC++ was stupid or if GCC was stupid. So could someone clarify this: By the C++ standard which also should be the same with the C standard, is it correct to allocate an array when it's size is based on a non-constant variable? And if not, what is the most appropriate way to fix this?
C++/C89 it does NOT work. C99 it can work (assuming you change std::cout and stuff to printf).
C++/C89 it does NOT work. C99 it can work (assuming you change std::cout and stuff to printf).
Neither GCC nor VC++ are being stupid. This is what's called a language extension. You can use them or or ignore them, but you should at least know that they are extensions so that you can avoid them when necessary.

As for how to do this the portably, the answer is a few posts back.
im using Code::Blocks IDE i really like it... so, is useing these things like, hard on memory or speed or anything?
Is non-standard. This is enough to be avoided
Topic archived. No new replies allowed.