gggg77777
gggg77777

Reputation: 3

C++ array assignment gives compiler error

When i try to assign values to an array like this:

int ar[5] = {18,19,20,21,22,23};

I get a compiler error: too many initializers for 'int [5]'

But when I do it like this:

int ar[5];
ar[0] = 12, ar[1] = 13, ar[2] = 14, ar[3] = 15, ar[4] = 16, ar[5] = 17;

Everthing is fine and the program runs fine and outputs correct results, am I doing something wrong or?

Upvotes: 0

Views: 159

Answers (2)

user13387119
user13387119

Reputation:

Int[5] can only hold 5 elements but you are giving it 6. Hence error. use ar[6] or remove an element from the array.

Second case is undefined behavior, the compiler just calculates and places the value without checking if it belongs to the array, and may likely overwrite any other variable data.

Upvotes: 0

cigien
cigien

Reputation: 60208

Yes, you are doing something wrong here:

ar[5] = 17;

by invoking undefined behavior. You can't index the 6th element (which is stored at the index 5) of an array containing only 5 elements.

The fact that the program runs and gives the correct output is an accident. You can't rely on this, and the program is fundamentally broken.

Upvotes: 4

Related Questions