Difference between array [n] and array []?

Is there a difference between for example

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

and

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

The compiler needs to calculate the number of elements by its own attribute for the first case, and this may take some time ( {...} out of 1234332534 elements), so the second case is more effective than the first?

+6
source share
5 answers

It makes no difference if the explicit count of elements between [] matches the number of initializers between {} .

The issue of "effectiveness" is controversial. The size of the array is determined at compile time, which means that it does not affect the efficiency of the code. And since in any case, the compiler will have to parse the list of initializers in any case, it does not have a real impact on compilation efficiency.

+5
source

This is an array declaration:

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

is the same as:

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

The number of elements is computed at compile time, so the runtime is not associated with this.

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

+8
source
  • There is no difference in the final result; however, the first form is easier to write and maintain, because you do not need to manually count the elements.
  • The compiler probably should still count the elements: it should determine if they are larger, because it is a compilation error, and if they are smaller than the others, then they should be initialized to zero.
  • In any case, such an account is executed at compile time, so there is no effect on the performance of the generated executable file.
  • In the general case, you never have very large arrays created on the stack or in the form of global variables (since in the general case large distribution packages are not executed, and large arrays in the form of global variables lead to huge executable files † ).
  • And even if you manage to get the compiler to accept a static / local array of 1234332534 elements, counting the elements is likely to be the last of the performance problems of this compilation.

†. On the other hand, large global arrays are how binary resources are often included in the firmware in order to sparkle on embedded devices. But I do not think that someone will consider this brute force method for something more than a few megabytes.

+2
source

It makes no difference, except that you, the programmer, should not determine how many elements are in the array. The compiler is still going to count the elements in order to allocate the desired amount, so both compilers must compile the same amount of time.

+1
source

In the second case, the precompiler will catch an error if the wrong number of values ​​are specified to initialize the memory. This is pretty much it.

0
source

Source: https://habr.com/ru/post/896361/


All Articles