C-style arrays come from C language and are part of C++ language core. This means we do not have to #include any header file like we do for std::array, std::vector or any other container class.
Creating a C-style array
We can create a C-style array as shown below:
int arr[2]{1, 2}; // list initialized (preferred)
int arr2[2]{}; // value initialized
int arr3[2] = {1, 2}; // copy list initializedWe provide array length inside the braces [] followed by initialization list. C-style arrays are aggregate so they work with aggregate initialization.
When we provide the initializers list, we can omit length in braces and let compiler deduce the length from the numbers of values in the list. For example:
int array[]{1, 2, 3};One more thing to note that the length of the array has to be a constexpr:
int length{3};
int array[length]{1, 2, 3};it would fail if compiled, as length is not constexpr.
Note
There may be chance that the above may compile successfully on your machine. This maybe because some compiler allow using non-constexpr length for arrays for compatibility with C99 feature called variable length arrays(VLAs).
Variable length arrays are not part of C++ and should not be used in C++. You can configure the compiler to disable this extension. If you using
g++compiler, you can using flag-pedantic-errorsthat disables non-standard extension and-Werror=vlathat treats variable length arrays as error.
auto does not work with C-style arrays
We can’t use auto to define C-style arrays because CTAD only works with class templates and C-style arrays are not class template:
auto arry[]{1, 2, 3}; // fails
int arry[]{1, 2, 3}; // worksSo, we need to use explicit types.
C-style arrays do not support assignment
Once a C-style array is initialized, it can’t be reassigned because C-style arrays are not modifiable lvalues and assignment requires left hand operand to be modifiable lvalue.
For example:
int arry[]{1, 2, 3};
array = {1, 2, 3}; // assignment doesnt work