开发者

Difference between array[n] and array[]?

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)开发者_JS百科, so second case is efficient than the first?


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.


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.


  1. There's no difference in the final result; still, the first form is easier to write and to maintain, because you don't have to count manually the elements.
  2. The compiler probably has to count the elements anyway: it must detect if they are more because it's a compilation error, and if they are less the others must be initialized to zero.
  3. Anyhow, such count is done at compile time, so there's no impact into the performance of the generated executable.
  4. In general you never have very big arrays created on the stack or as globals (because generally big stack allocations fail, and big arrays as globals will result in enormous executables).
  5. And even if you managed to make the compiler accept a static/local array of 1234332534 elements, the counting of the elements will probably be the last of the performance problems of this compilation.

†. 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜