變數作用範圍

在 86Duino 中使用的 C 語言變數,可依照其作用域的不同來加以區分,這點與所有變數皆為全域變數的早期程式語言 BASIC 有所不同。

全域變數是可以被程式中的所有函式使用的,而區域變數則只能被宣告它的函式使用;在 86Duino 的環境中,所有被宣告在函式之外的變數 (例:setup()loop()、等等…) 為全域變數。.

當程式碼變得更大更複雜之後,區域變數可以確保各函式內的變數只會被自身函式存取,這能預防程式的錯誤,讓一個函式不會不小心去存取到其他函式在使用的變數。

for 迴圈內也可以宣告一個變數並給定初值,這樣可以讓這個變數只能在該 for 迴圈中存取。

範例

int gPWMval;  // 任意的函式都可以使用它

void setup()
{
  // ...
}

void loop()
{
  int i;    // "i"是只存在"loop"函式中的變數
  float f;  // "f"是只存在"loop"函式中的變數
  // ...

  for (int j = 0; j <100; j++){
  // 變數 j 只能在 for 迴圈中存取
  }
}

語法參考主頁面

本頁由熱血青年 LBU 譯自英文版。

The text of the 86Duino reference is a modification of the Arduino reference, and is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.