0

I've noticed that this code:

#include <iostream>
using namespace std;

int main () {
    int k;
    cin >> k;
    int n[k];
    for (int i = 0; i < k; i++)
        n[i] = i;

    for (int i = 0; i < k; i++)
        cout << n[i] << " ";
    return 0;
}

compiles just fine. Could anyone clarify on this, because as far as I'm aware, static arrays must have a constant as their size.

0

1 Answer 1

6

clang and gcc support variable length arrays as an extension in C++ even though it is a C99 feature. If you compile with the -pedantic flag they will both provide a warning for example this is what clang says:

warning: ISO C++ forbids variable length array 'n' [-Wvla]
 int n[k];
        ^

You can turn it into an error using the -pedantic-errors flag.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, is there a way to enable the -pedantic by default, I've only recently switched to clang?
It is going to depend on what interface you are using. I am usually using a command line so I would have to figure it out myself.
@Frows Generally there's no way to set implicit default flags. Clang wants all flags to be supplied every time explicitly, though you can automate that part. Either you automate your build process (using Makefiles, an IDE, or another build tool) and add the flag there, or you create an alias in the shell, or you pass it every time. Just make a habit of adding -Wall to all compiler invocations :-)
I'm using NetBeans 7.4, works fine with terminal but I'm looking into making it enabled by default
@Frows what delnan said pretty much sums it up but NetBeans probably has a way to set that up.
|