THE WORLD'S LARGEST WEB DEVELOPER SITE

C++ Omit Array Size


Omit Array Size

You don't have to specify the size of the array. But if you don't, it will only be as big as the elements that are inserted into it:

string cars[] = {"Volvo", "BMW", "Ford"}; // size of array is always 3

This is completely fine. However, the problem arise if you want extra space for future elements. Then you have to overwrite the existing values:

string cars[] = {"Volvo", "BMW", "Ford"};
string cars[] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};

If you specify the size however, the array will reserve the extra space:

string cars[5] = {"Volvo", "BMW", "Ford"}; // size of array is 5, even though it's only three elements inside it

Now you can add a fourth and fifth element without overwriting the others:

cars[3] = {"Mazda"};
cars[4] = {"Tesla"};
Run example »

Omit Elements on Declaration

It is also possible to declare an array without specifying the elements on declaration, and add them later:

string cars[5];
cars[0] = {"Volvo"};
cars[1] = {"BMW"};
...
Run example »