Local & global variables

Every loop this will add 1 to the variable a.

int a;

void loop() { a++; Serial.println(a); }

This will not add 1 to the variable with every loop. void loop() { int a; a++; Serial.println(a); }

Is there way I can keep the variable local and make it work?

doug_army: This will not add 1 to the variable with every loop. void loop() { int a; a++; Serial.println(a); }

Is there way I can keep the variable local and make it work?

It actually does add 1 to the value of 'a'. Unfortunately, the value of 'a' is undefined every time the loop() function is called.

try:

static int a = 0;

Thank you so much that did the trick.

gfvalvo: It actually does add 1 to the value of 'a'. Unfortunately, the value of 'a' is undefined every time the loop() function is called.

In fact the language definition says that what happens is each time round the loop a new local variable is created, which happens to have the same name as one from the last time round the loop, and is undefined in value. At the end of the loop body the variable is notionally destroyed.

This matters with class-valued variables as the constructor and destructors will be called automatically.

'static', when used inside any function limits the visibility of the variable to the body of the function, otherwise its global just like a static variable at top level.

MarkT: 'static', when used inside any function limits the visibility of the variable to the body of the function, otherwise its global just like a static variable at top level.

Nope any variable defined within a function (static or not) is local and only visible within that function. 'static' makes its value persist between calls to the function.

You boys just said the same thing.

-jim lee

jimLee: You boys just said the same thing.

Nope.

MarkT’s definition says static restricts the scope. And implies if it’s not static then it’s the same as a global... “otherwise its global just like a static variable at top level.”

That’s obviously not the case. The scope of local variables, static or not, is always the function/code block they are defined in.

pcbbc: Nope.

MarkT’s definition says static restricts the scope. And implies if it’s not static then it’s the same as a global... “otherwise its global just like a static variable at top level.”

That’s obviously not the case. The scope of local variables, static or not, is always the function/code block they are defined in.

Right. And, applying the 'static' designation to a global variable does something completely different. It restricts the scope of that variable to the file ("compilation unit") where it's defined. Otherwise, it's available as a global variable in all other files (if properly declared).