java - 初始化数组是否保留其在 C/C++ 和类似语言中的顺序?

标签 java c++ c arrays programming-languages

<分区>

假设我有一个 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 页。

关于java - 初始化数组是否保留其在 C/C++ 和类似语言中的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36179444/

相关文章:

c++ - 我如何在 C++ 中的字符串中嵌入 NULL 字符?

c++ - 在有向循环图中找到所有可能的路径

c - 访问二维数组中的越界单元格

java - 测试期间未正确读取 MessageSource

java - SAX解析器,解析后新行被删除,我可以保留它们吗? ( )

java - 井字游戏电脑玩家(非 AI)

c++ - OpenCV中两个数组的互相关

c++ - 为什么在引用计数器上需要存储顺序限制?

c - 段错误(核心已转储)。堆排序

java - 使用 "JSP Document"/"JSP in XML notation"是否意味着输出 XHTML?