Loop() is not really looping, is it?

I found something interesting about the loop() procedure.

I have a very simple code like this:

  loop() {
  int t;

    Serial.println(t);
    t++;
  }

The println will always come up with 0.
Meaning, either the loop is going all the way back to the initialization of t, or the procedure is called from somewhere deeper inside boot loader or something, and the actual looping takes place there?
Something is, after all taking, care of, Startup() is run first.

Making t a global variable will fix that glitch.

Hello walker1
Declare the variable t to static otherwise the variable will be 0 all the time.

  loop() {
  static int t;

    Serial.println(t);
    t++;
  }

Have a nice day and enjoy coding in C++.
Дайте миру шанс!

p.s. Take a view here

2 Likes

You need to read up on c/c++ variable scope. It is working precisely as the c/c++ language spec says it should.

1 Like

loop() is a function called "from an external" loop!
It does not mean it loops the code inside the function.
It means: the loop() function is called in a (external) loop.

  • loop() is called from the RTOS task manager in a cyclic way (from the outside)

  • so, loop() called is like any other function call: local (auto) variables are allocated and released
    at the end of loop (again and again)

int t; is an uninitialized, random variable
Bear in mind: "somebody" calls this loop(), e.g. every X milli-seconds by the RTOS.
Your variable t is never initialized before used.
And at the end of loop() (the hidden return there, the last curly bracket) the variable t is
destroyed, memory released, value lost etc.

==> so, in every call of this function - "in your assumed loop" - t is totally random and different.

If you want to have t counting - do this code:

  loop() {
  static int t = 0;

    Serial.println(t);
    t++;
  }

This should now properly count.

There is no RTOS; it just runs from a normal c main() function which calls setup() once and loop() from a perpetual for():

setup();
    
	for (;;) {
		loop();
		if (serialEventRun) serialEventRun();
	}

Yes, this is a good example how loop() is used. We can see, the loop is "external" (a caller calling loop()). And loop is just a regular function. All the issues to bear in mind with local variables inside loop().

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.