Question:

How is an array initialized in C++ language ?

Show Hint

For basic C++ arrays, remember the pattern: `type name[size] = { value1, value2, ... };`. The square brackets `[]` are key for arrays.
  • int a[3] = \{1, 2, 3\};
  • int a = \{1, 2, 3\};
  • int a[] = new int[3];
  • int a(3) = \{1, 2, 3\};
Hide Solution
collegedunia
Verified By Collegedunia

The Correct Option is A

Solution and Explanation

Step 1: Review C++ array initialization syntax. In C++, a static array is declared with its type, name, and size in square brackets. It can be initialized at the time of declaration using an initializer list in curly braces `{}`.
Step 2: Analyze the options.

(A) \text{int a[3] = \{1, 2, 3\};}: This is the correct and complete syntax. It declares an integer array named `a` of size 3 and initializes it with the given values.
(B) \text{int a = \{1, 2, 3\};}: This is incorrect. The square brackets `[]` for the size are missing.
(C) \text{int a[] = new int[3];}: This is incorrect syntax. `new int[3]` is for dynamic allocation and would be assigned to a pointer, e.g., `int a = new int[3];`.
(D) \text{int a(3) = \{1, 2, 3\};}: This is incorrect. Parentheses are not used for declaring array sizes.
Another valid syntax is `int a[] = {1, 2, 3};` where the compiler infers the size from the initializer list. However, option (A) is the most explicit and correct choice provided.
Was this answer helpful?
0
0