I was used to using
new int[] {1,2,3,4,5};
for initializing array. But it seems nowadays, this does not work anymore, i have to explicitly state how many elements there are, with
new int[5] {1,2,3,4,5};
so compilers forgot how to count ?
And to make this a closed question, is there a way to omit the number of elements ?
The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.
Initializing arrays But the elements in an array can be explicitly initialized to specific values when it is declared, by enclosing those initial values in braces {}. For example: int foo [5] = { 16, 2, 77, 40, 12071 };
Using default values in initialization of array For double or float , the default value is 0.0 , and the default value is null for string. Type[] arr = new Type[capacity]; For example, the following code creates a primitive integer array of size 5 . The array will be auto-initialized with a default value of 0 .
This has never worked in the current version of C++, you have only been able to zero-initialize (or not initialize) dynamically allocated arrays.
What has always worked is non-dynamically allocated array initialization:
int myarray[] = {1, 2, 3, 4, 5};
Perhaps you are confusing it with this?
Even in C++0x it is not legal syntax to omit the explicit array size specifier in a new expression.
C++ have never allowed to initialize array with an unknown size of elements like above. The only 2 ways I know, is specify the number of elements or use pointers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With