Please note, this is a STATIC archive of website www.w3schools.com from 05 May 2020, cach3.com does not collect or store any user information, there is no "phishing" involved.
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 »