Variables in the C++ programming language, which Arduino uses, have a property called scope. This is in contrast to early versions of languages such as BASIC where every variable is a global variable.

There are two types of variables: global variable and local variable

  • A global variable is the variable declared outside of all functions (e.g. setup(), loop(), etc. ). The global variable can be accessed by every functions in a program.
  • A local variable is the variable declared inside a function or a block of code (inside a curly brackets). The local variable only visible to the function or block of code in which they are declared.

When programs start to get larger and more complex, local variables are a useful way to insure that only one function has access to its own variables. This prevents programming errors when one function inadvertently modifies variables used by another function.

It is also sometimes handy to declare and initialize a variable inside a for loop. This creates a variable that can only be accessed from inside the for-loop brackets.

Example Code

int gPWMval; // a global variable: all functions can access this variable void setup() { // ... } void loop() { int i; // a local variable: i is only visible inside of loop() function float f; // a local variable: f is only visible inside of loop() function // ... for (int j = 0; j < 100; j++) { // a local variable: j can only be accessed inside the for-loop brackets } }

See Also


Arduino UNO R3
Arduino Starter Kit
Please note: These are Amazon affiliate links. If you buy the components through these links, We will get a commission at no extra cost to you. We appreciate it.