-3

I have been trying to learn arrays and I can't seem to define an array.

const int size = 10;
??[size];

Can anybody spot my mistakes? Thank You.

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141

2 Answers2

2

To declare an array using a constant, you should use this syntax:

// constexpr is explicitly compile time constant
constexpr int size = 10;
int my_array[size]; // int array, can be changed to float

For dynamic array, use vector:

int size = ...;
std::vector<int> my_array;
array.resize(size);

You can also use modern statically sized array:

constexpr int size = 10;
std::array<int, size> my_array;
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
  • Why not `std::vector array(size);`? Also, the `constexpr` is not required. For integer types, just `const` works. – NathanOliver Feb 07 '22 at 20:23
  • @NathanOliver I avoid confusion with initializer list. When a class has overloaded constructors with initializer list that could be in conflict, I simply not use those constructors in answers, especially to beginners. Also, the parens `()` are too close to `[]`, which a very beginner could confuse. – Guillaume Racicot Feb 07 '22 at 20:25
  • @NathanOliver Of course, if `[size]` could be placed on the type, and constructors would never change when you change syntax between `{}` and `()`, and vexing parse woudn't be a problem, I would simply use the constructor. – Guillaume Racicot Feb 07 '22 at 20:28
1
const int size = 10;
type array[size];

Is what you want. Substitute type for any type (i.e. int, float, bool etc.).

In this case, specifying array size using a const variable is valid, but there are many cases where it isn't. You'd probably want to learn the difference between const and constexpr.

Also, instead of learning by asking questions here, try finding a good c++ source: a book, online article series or a video tutorial. It'll definitely accelerate your education.