if I declare an automatic (local) variable inside loop() body, is that variable destroyed each time the function body ends? I suppose it because the lifetime of a local variable ends when it's block of code is terminated.
As an example, in:
void setup()
{
pinMode(13, OUTPUT);
}
void loop()
{
int a = 13;
digitalWrite(a, HIGH);
delay(1000); // Wait for 1000 millisecond(s)
digitalWrite(a, LOW);
delay(1000); // Wait for 1000 millisecond(s)
}
Does the variable a gets destroyed and declared in each iteration of loop()?
Just one more question: is there a problem if I insert pinMode(13, OUTPUT); inside loop() body instead of setup()'s one like the following code?
void setup()
{
}
void loop()
{
int a = 13;
pinMode(a, OUTPUT);
digitalWrite(a, HIGH);
delay(1000); // Wait for 1000 millisecond(s)
digitalWrite(a, LOW);
delay(1000); // Wait for 1000 millisecond(s)
}
ripper_roo:
I suppose it because the lifetime of a local variable ends when it's block of code is terminated.
Compilers are very efficient now. A local variable might not even use RAM when the compiler figures out it can just use a processor register to hold the value and in some cases the variable is optimized away. This allows you to write code that is easy to understand by using nice variable names and the compiler creates something that executes fast and uses as little memory as necessary.
This will teach you how to avoid using the delay function. This is often the cause of issues for beginners because it just stops the sketch and wastes time that can be spend doing something else.
Even though the "creation" and "destruction" sounds like a lot of activity, the creation and destruction of a variable not declared 'static' in a function, actually has very low overhead at run time. The only difference between those and global variables in this way, is that the stack pointer is incremented when calling to allocate more room on the stack. This can be done just once, no matter how many locals there are, because it's just a different stack offset.
aarg:
Even though the "creation" and "destruction" sounds like a lot of activity, the creation and destruction of a variable not declared 'static' in a function, actually has very low overhead at run time. The only difference between those and global variables in this way, is that the stack pointer is incremented when calling to allocate more room on the stack. This can be done just once, no matter how many locals there are, because it's just a different stack offset.
Does the variable a gets destroyed and declared in each iteration of loop()?
Despite its name the loop() function does not loop. Rather it is called repeatedly from the hidden main() function, so any local variable declared in it behaves like a local variable in any function
Okay, just kidding... the stack is a FILO structure maintained in memory, that allows the processor to remember where it came from when it calls a function. Variables sent to and from the function are also placed there.