Try   HackMD
tags: 雜~~瓦魯多~~筆記

細說C++變數命名規則

在課程中提到變數宣告,雖然變數的名稱基本上是可以依自己的需求命名,但依舊有一些規則與禁忌。

命名基本規則

符號

一般來說,命名時經常使用的字元有以下幾個:

  • 大寫 A~Z
  • 小寫 a~z
  • 底線 _
  • 數字 0~9

要注意的是,就算是一個英文字母 大小寫不同 ,也會被視為是不同的名稱,因為C++是一種具有 大小寫敏感性 (case sensitive)的語言。

而以這些字元進行命名時,也有一些應遵守的規則與禁忌。

禁忌

不可使用重複名稱

命名兩變數時,不可使用同一個名稱。

若是兩變數擁有相同名稱,在使用時,編譯器會無法分辨兩個變數,即使兩變數型態不同也會無法識別。

錯誤範例如下:

int name; char name; //錯誤,name這名稱已被使用過,不可再次用來命名不同變數

數字不可為第一位

變數名稱雖然可以包含數字,但不可在第一位。

錯誤的範例如下:

  • 12dd
  • 2nd_var
  • 5th_arr

而這些是可使用的名稱:

  • num1
  • arr57
  • DP_01

名稱不可與保留字相同

保留字,即為在C++中具有特殊意義的詞,在後續會有詳細列表。
變數命名時應避開保留字,以免編譯器將其誤判為指令。

以下舉幾個常見的例子:

  • return 意思為 回傳 ,在主程式結尾都會出現。
  • cout 即為常用的 輸出
  • intchar 這類的 變數型態名稱 亦不可使用。

保留字列表

前面提到過的保留字,這裡為各位整理為表格,方便在練習時參考對照使用。
有出現在表格內的字詞,不可用於命名變數。

變數與範圍相關

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

修飾詞相關

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

流程控制與迴圈相關

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

運算子與條件判斷

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

物件相關

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

命名習慣

一般來說,命名時會以簡單的命名輔以縮寫,重點在於 能使人理解該變數用途

良好的命名習慣可以增進寫程式的效率,也能增加程式的可讀性,使程式易於除錯與維護。

字詞分隔

若是名稱有多個英文字詞,可以用底線 _ 分隔。
如: upper_casearray_edge

或是以大小寫區別各字詞。
如: UpperCaseArrayEdge

縮寫

有些變數名稱過於冗長,這時可以將其適當縮寫。

常用的名稱縮寫如下:
number -> num
string -> str
array -> arr
pointer -> ptr
variable -> var

或是取首字母作為縮寫,如:
dynamic_programming -> DP
fibonacci -> F

當然這些只是本人的小小習慣,若是有更適合自己的一套習慣,那也是很好的,畢竟重點在於易讀與習慣操作。