Home > Article > Backend Development > How to Efficiently Initialise Arrays Allocated with the `new` Operator in C ?
Query:
Beginning C learners often wonder about the best practices for initialising arrays allocated with the new operator. Is it preferred to manually loop through and set each element to 0, or is there a more efficient method?
Answer:
Surprisingly, C offers a dedicated syntax for value-initialising arrays:
new int[10]();
It's crucial to include the empty parentheses; using (0) or other inputs would not work with this technique.
This behaviour is outlined in ISO C 03 5.3.4[expr.new]/15, which specifies that a new expression with a () initialiser will perform value-initialisation, regardless of the array type.
By contrast, the (expression-list) form of initialisation comes with restrictions that disallow array types.
The above is the detailed content of How to Efficiently Initialise Arrays Allocated with the `new` Operator in C ?. For more information, please follow other related articles on the PHP Chinese website!