假设我有一个 C/C++ 数组:
int myArray[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
在 Java 中相同:
int[] myArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
以及其他编程语言中的等价物。
是否保证元素总是按照我在初始化时键入的顺序排列?例如:1、2、3、4、5、6、7、8、9、10
。
注意:我已经问过this question特定于 Java 编程语言,我知道这是真的。但我想知道这种行为是否是任何(或大多数)编程语言的规则,而且我不确定编辑是否是提出这个问题的最佳方式。
让我们听听 C 语言的创造者对此有何看法:
An array may be initialized by following its declaration with a list
of initializers enclosed in braces and separated by commas. For
example, to initialize an array days with the number of days in each
month:
int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
When the size of the array is omitted, the compiler will compute the
length by counting the initializers, of which there are 12 in this
case. If there are fewer initializers for an array than the specified
size, the others will be zero for external, static and automatic
variables. It is an error to have too many initializers.
There is no
way to specify repetition of an initializer, nor to initialize an
element in the middle of an array without supplying all the preceding
values as well.
Character arrays are a special case of initialization;
a string may be used instead of the braces and commas notation:
char pattern = "ould";
is a shorthand for the longer but equivalent
char pattern[] = { 'o', 'u', 'l', 'd', '\0' };
In this case, the array size
is five (four characters plus the terminating '\0').
C BRIAN W KERNIGHAN 和 DENNIS M RITCHIE,第二版,第 95 页。