The most basic difference is of scope.
In the first case, you are declaring a global variable. It is a variable that is accessible in every scope after its definition.
void setup()
{
Serial.begin(9600);
}
void inc();
int count = 0;
void loop()
{
Serial.println(count);
count++;
inc();
delay(500);
}
void inc() //Can edit the value of count
{
count=count+1;
};
In the second case, you are declaring a static variable with local scope. The variable will persist for the entire program run similar to global variables, but will be accessible only in the code block it is declared in. This is the same example, with only one change. count
is now declared as a static variable inside loop
.
void inc();
void loop()
{
static int count = 0;
Serial.println(count);
count++;
inc();
delay(500);
}
This will not compile as the function inc()
does not have access to count
.
Global variables, however seemingly useful, come with some pitfalls. These can even cause damage when it comes to writing programs that can interact with the physical surroundings. This a very basic example of something that is quite likely to happen, as soon as programs start getting larger. A function may inadvertently change the state of a global variable.
void setup()
{
Serial.begin(9600);
}
void another_function();
int state=0;
void loop()
{
//Keep toggling the state
Serial.println(state);
delay(250);
state=state?0:1;
//Some unrelated function call
another_function();
}
void another_function()
{
//Inadvertently changes state
state=1;
}
Such cases are very hard to debug. This type of problem however, can easily be detected, by simply using a static variable.
void setup()
{
Serial.begin(9600);
}
void another_function();
void loop()
{
static int state=0;
//Keep toggling the state
Serial.println(state);
delay(250);
state=state?0:1;
//Some unrelated function call
another_function();
}
void another_function()
{
//Results in a compile time error. Saves time.
state=1;
}