Skip to content

Instantly share code, notes, and snippets.

@char-1ee
Last active June 29, 2022 17:07
Show Gist options
  • Save char-1ee/d81bd92fca9f3e905679461d5a2c7ddf to your computer and use it in GitHub Desktop.
Save char-1ee/d81bd92fca9f3e905679461d5a2c7ddf to your computer and use it in GitHub Desktop.

In C++, variable length arrays are not legal. g++ allows this as an "extension" (because C allows it), so in g++ (without being
-pedantic about following the C++ standard), you can do:

int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++

If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:

int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!

Or, better yet, use a standard container:

int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>

If you still want a proper array, you can use a constant, not a variable, when creating it:

const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)

Similarly, if you want to get the size from a function in C++11, you can use a constexpr:

constexpr int n()
{
    return 10;
}

double a[n()]; // n() is a compile time constant expression

References: Array[n] vs Array[10] - Initializing array with variable vs numeric literal
Related reading: Why can't I create an array with size determined by a global variable?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment