Variable scope

From Microduino Wiki
Jump to: navigation, search

Variable scope

Variables of C language in Arduino have a property named scope. This is in contrast with the language similar to BASIC where all variables are global variables.

The global variables in a program can be called by all functions. Local variables are only visible in the functions which declare them. In Arduino environment, any variables declared outside the functions(for example, setup(),loop() and so on)are all global.

When the program gets bigger and more complex, the local variable is a effective method to determine each function can only access their own variables, which can prevent the program error of which a function inadvertently modifies the variable used in another function.

Sometimes, declaring and initiating a variable in a for loop is also very convenient, which will create a variable can only be accessed from the brackets of the for loop.

  • Example
int gPWMval;  // any function can invoke this variable
 
void setup()
{
  // ...
}
 
void loop()
{
  int i;    // "i"  can only be used within function  "loop" 
  float f;  // "f"  can only be used within function  "loop" 
  // ...
 
  for (int j = 0; j <100; j++){
    //Variable j can only be accessed in the braces of the loop
  }
}

[Return to Arduino Syntax Manual]