Variables

A variable is a way of naming and storing a numerical value for later use by the program.A variable needs to be declared and optionally assigned to the value needing to be stored. The following code declares a variable called inputVariable and then assigns it the value obtained on analog input pin 0:

int inputVariable = 0; // declares a variable andassigns value of 0

inputVariable = analogRead(2); // set variable to value ofanalog pin 2

variable declaration

All variables have to be declared before they can be used. Declaring a variable means defining its value type, as in int, long, float, etc., setting a specified name, and optionally assigning an initial value. This only needs to be done once in a program but the value can be changed at any time using arithmetic and various assignments.

The following example declares that inputVariable is an int, or integer type, and that its initial value equals zero. This is called a simple assignment.

 int inputVariable = 0;

variable scope

,p>A variable can be declared at the beginning of the program before void setup(), locally inside of functions, and sometimes within a statement block such as for loops. Where the variable is declared determines the variable scope, or the ability of certain parts of a program to make use of the variable.

A global variable is one that can be seen and used by every function and statement in a program. This variable is declared at the beginning of the program, before the setup() function.

A local variable is one that is defined inside a function or as part of a for loop. It is only visible and can only be used inside the function in which it was declared.

int value;   // global variable : 'value' is visible to any function
void setup()
{
// no setup needed
}
void loop()
{
for (int i=0; i<20;)
{
i++;
}
float f;       // local variable : 'f' is only visible inside loop
}

Next : Data Types