DevAcademia lesson/C++ Basics
Omit Array Size
Topic progressTopic 54 of 109 - 50% complete
~7 min lesson25 learning blocks5 code examples1 checks/interactions
Lesson outline
Implicit Size Determination
C++ allows omitting the array size when an initializer list is provided. The compiler counts the elements and sets the size automatically.
Technical Implementation Details
When the size is omitted:
- The compiler creates a complete array type with N elements
- The element count becomes part of the array type
- The size is fixed at compile time
- The array cannot be resized or reassigned later
Aliases and Typedefs
You can simplify array declarations with aliases, but the bound must be part of the type; alternatively, prefer std::array for safer, modern code.
Common Use Cases
| Use Case | Example | Benefit |
|---|---|---|
| Lookup tables | const char* colors[] = {"red", "green", "blue"}; | Easier to extend |
| Test data | float testCases[] = {1.1, 2.2, 3.3}; | No need to count elements |
| String arrays | std::string messages[] = {"Hello", "World"}; | Clear and concise |
| Binary buffers | unsigned char header[] = {0x89, 'P', 'N', 'G'}; | Exact binary specification |
Limitations and Considerations
Restrictions when omitting array size:
- An initializer must be provided at the point of declaration
- In function parameters, arrays decay to pointers; 'void func(int param[])' is allowed but size info is lost—use 'void func(int (¶m)[N])' to retain the bound
- Not valid for class member declarations without an explicit size
- Cannot be used with 'new[]' (size must be specified)
- Does not work with 'auto' (use 'std::array' or 'std::to_array')
Real-World Example: Error Message Lookup
Practical use case: storing error messages without manually specifying array size.
Was this topic clear?