隱式變數型別
當 Fortran 最初開發時,記憶體非常寶貴。變數和過程名稱最多可包含 6 個字元,變數通常是隱式輸入的。這意味著變數名的第一個字母決定了它的型別。
- 以 i,j,…,n 開頭的變數是
integer
- 其他一切(a,b,…,h 和 o,p,…,z)都是
real
以下程式是可接受的 Fortran:
program badbadnotgood
j = 4
key = 5 ! only the first letter determines the type
x = 3.142
print*, "j = ", j, "key = ", key, "x = ", x
end program badbadnotgood
你甚至可以使用 implicit
語句定義自己的隱式規則:
! all variables are real by default
implicit real (a-z)
要麼
! variables starting with x, y, z are complex
! variables starting with c, s are character with length of 4 bytes
! and all other letters have their default implicit type
implicit complex (x,y,z), character*4 (c,s)
**隱式打字不再被視為最佳實踐。**使用隱式型別很容易出錯,因為錯別字可能會被忽視,例如
program oops
real::somelongandcomplicatedname
...
call expensive_subroutine(somelongandcomplEcatedname)
end program oops
這個程式很樂意執行並做錯事。
要關閉隱式型別,可以使用 implicit none
語句。
program much_better
implicit none
integer::j = 4
real::x = 3.142
print*, "j = ", j, "x = ", x
end program much_better
如果我們在上面的程式 oops
中使用了 implicit none
,編譯器會立即注意到,併產生錯誤。