Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between array[n] and array[]?

Tags:

c++

arrays

c

Is there any difference between, for example

int array[]={1, 2, 3, 4, 5};

and,

int array[5]={1, 2, 3, 4, 5};

Compiler needs to calculate number of elements by self for the first case, and that can take a some time ({...} of 1234332534 elements), so second case is efficient than the first?

like image 426
Srle Avatar asked Aug 31 '11 22:08

Srle


2 Answers

This array declaration:

int array[] = {1, 2, 3, 4, 5};

is the exact same as:

int array[5] = {1, 2, 3, 4, 5}; 

The number of elements is calculated at compile time, so there's no runtime cost associated with that.

The advantage of the first declaration is that it does not require the programmer to manually count the number of elements, so it's a more efficient array declaration in that sense.

like image 66
In silico Avatar answered Sep 20 '22 17:09

In silico


There's no difference, as long as the explicit element count between [] is the same as the number of initializers between the {}.

The question about "efficiency" is moot. The array size is determined at compile time, which means it has no impact on the efficiency of the code. And since in any case the compiler will have to parse the initializer list anyway, it has no real impact on the efficiency of the compilation.

like image 41
AnT Avatar answered Sep 24 '22 17:09

AnT