Reputation: 10496
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?
Upvotes: 6
Views: 390
Reputation: 126787
†. on the other hand, big global arrays is how binary resources are often included into firmware to be flashed onto embedded devices. But I don't think that anyone will consider this brute-force method for anything bigger than several MBs.
Upvotes: 2
Reputation: 52159
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.
Upvotes: 8
Reputation: 11
In second case the precompiler will catch an error if wrong number of values is given to initialize the memory. That is pretty much it.
Upvotes: 0
Reputation: 320451
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.
Upvotes: 5
Reputation: 57774
No difference, except that you, the programmer, does not have to determine how many elements are in the array. The compiler is still going to count the elements to allocate the proper amount, so both take the compiler the same length of time to compile.
Upvotes: 1