Re: [問題] 關於陣列從0或1開始算起的好處
我也不知道為什麼當初要這樣選, 但是我試著從 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
討論串 (同標題文章)
完整討論串 (本文為第 2 之 4 篇):