C++ Omit Array Size

In C++, when defining an array, you don’t have to specify its size if you directly initialize it with values. The compiler automatically determines the size based on the number of provided elements.

Tutorials dojo strip



Omitting Array Size on Declaration

Instead of explicitly setting a size, you can let C++ infer it:

string bikeBrands[] = {"Yamaha", "Ducati", "Kawasaki"};

This is equivalent to:

string bikeBrands[3] = {"Yamaha", "Ducati", "Kawasaki"};

However, explicitly defining the array size is considered better practice, as it helps prevent potential errors.




Declaring an Array Without Initializing Elements

You can declare an array without specifying values immediately and assign them later:

string bikeBrands[5];
bikeBrands[0] = "Yamaha";
bikeBrands[1] = "Ducati";
bikeBrands[2] = "Kawasaki";
bikeBrands[3] = "Honda";
bikeBrands[4] = "Harley-Davidson";

Important: This approach only works if the array size is specified at the time of declaration.




Error When Omitting Size Without Initialization

If the array size isn’t provided, an error occurs:

string bikeBrands[];  // ❌ Error: Missing array size
bikeBrands[0] = "Yamaha";
bikeBrands[1] = "Ducati";

Error: "array size missing in 'bikeBrands'"




Fixed-Size Arrays vs. Dynamic-Size Vectors

In C++, arrays have a fixed size, meaning their capacity cannot change after declaration.

Fixed-Size Array Example

string bikeBrands[3] = {"Yamaha", "Ducati", "Kawasaki"};

// ❌ Error: Cannot add another element
bikeBrands[3] = "Honda";  
Tutorials dojo strip
Scroll to Top