作者lihgong (当宪兵是我一辈子的耻辱)
看板Programming
标题Re: [问题] 关於阵列从0或1开始算起的好处
时间Thu Aug 19 23:54:04 2010
我也不知道为什麽当初要这样选, 但是我试着从 Assembly 的角度来看这两种设计
----
如果从 assembly level 来看, 首先假设有个阵列
int a[16] // 位在 0x80000000
// 0x80000000, 0x80000004, ... 每个元素的 address
一般的阵列读取会用 ldr 指令
假设 r1 指向 a 的开头, 也就是 r1 == 0x80000000
假设 r2 是 index, r2 = [0, 1, 2, 3, ...]
那取出 a[index] 到 r9 的指令是
ldr r9, [r1, r2, LSL #2] // r9 = mem[ r1 + (r2<<2) ]
实际上这个 case 就是 index 从 0 开始, 只要一道指令就能存取阵列
----
接下来考虑阵列的 index 从 1 开始的话, 也就是 a[1] 会存取 a 的开头
为了简化讨论, 假设我们取出 a[] 开头的元素
这时候, r1 还是指向 a[] 的开头, 0x80000000
r2 是阵列的 offset, 这时他是 1 (因为 index 从 1) 开始
所以 CPU 要用两道指令才能去存取这个记忆体
add r3, r2, #-1 // r3 = r2 - 1
ldr r9, [r1, r3, LSL #2] // r9 = mem[ r1 + (r2-1)<<2 ]
----
编译器可能会编译出不同的指令, 这里只是举例
从 Assembly Level 来看这个问题, 阵列的 index 从 0 开始, 其实很"自然"
※ 引述《milonga332 ( U U)》之铭言:
: http://www.iis.sinica.edu.tw/~scm/ncs/2009/07/go-to-considered-harmful/
: 上面这个连结虽然是讨论GOTO
: 不过Dijkstra大师在里面说
: 『我以为到了现在,一个专业程式员该有高一点的自我要求了,阵列应该从0算起,
: 我以为到了现在,一个专业程式员该知道自然数从 0 开始的好处了』
: 但是我在看Core Java的时候作者又说了
: 『Java counts the code units in strings in a peculiar fashion:
: the first code unit in a string has position 0.
: This convention originated in C,
: where there was a technical reason for counting positions starting at 0.
: That reason has long gone away and only the nuisance remains.
: However, so many programmers are used to this convention that
: the Java designers decided to keep it.』
: 如果可以抛开历史因素之类相容问题的话
: 那麽阵列索引到底是从0开始计算好,还是从1开始计算好呢?
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 118.160.92.2