Project 08 - Question about the variable "currentTime"

There is a local variable created in the loop ( ) body named currentTime and is used to hold the current time since the Arduino first loaded up.

It is defined like this:

void loop ( ) { ** unsigned long currentTime = millis ( );** ** …** }

My question is if the body of the loop gets repeated, why isn't a new local variable created each time? Does the Arduino's IDE or the PC check if there are variables previously created in the last run of loop and if it finds one it doesn't create a new one?

Just had me thinking…


The loop() function is completely finished and started again. That means that the variable is created every time.

However, you don't have to worry about "creating" a variable, it is simpler than that. The unsigned long are 4 bytes and are filled with value of millis(). The millis() function is the function that returns the time since startup. Those 4 bytes could be kept in registers, or with 4 bytes on the stack.

So the millis() function is called, and the 4 bytes are kept in registers or in a location on the stack. That's all, there is nothing more to it.

Although the variable is created every time the loop runs, it is also destroyed as the loop ends (every time). So it's not an issue.

Thank you both for your explanation!