Why does a return in a void loop doesn't exit the function ?

Hello,

I always thought that a return exit a function like this.

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(2, OUTPUT);
  Serial.println("first");
  return;
  Serial.println("second");
}

the return exit the function so here it doesn't print "second" (which is normal).

But when you use it in a void loop like this.

Serial.println("loop");
  delay(1000);
  return;
  Serial.println("loop2");

It doesn't exit the void loop(), it runs "loop" again and again. How is this possible ?

Perhaps I'm not understanding you but the hint is in the name. Running again and again is what the special function loop() does. So a return exits it and it immediately loops round and starts again. That's why it's called loop().

Steve

Behind the scenes Arduino has a hidden "main" function. It works something like this...

void main()
{
  setup();
  while (true)
  {
    loop();
  }
}

slipstick: Perhaps I'm not understanding you but the hint is in the name. Running again and again is what the special function loop() does. So a return exits it and it immediately loops round and starts again. That's why it's called loop().

There's nothing actually "special" about loop(). The real answer is in the hidden (to most Arduino users) main() function. While hidden, it's there none the less and a look at its source code answers the question:

int main(void)
{
  init();

  initVariant();

#if defined(USBCON)
  USBDevice.attach();
#endif

  setup();

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

  return 0;
}

It doesn't exit the void loop(),

Oh yes it does. The return exits from loop() and returns back to the hidden main() function that called it. The main() function then calls it again so round and round it goes, hence the name of the function.

Thanks everyone, now I understand.

gfvalvo: There's nothing actually "special" about loop(). The real answer is in the hidden (to most Arduino users) main() function.

Matter of terminology perhaps but since no other functions are repeatedly called by main() or anything else I call that special. From an Arduino IDE point of view a user doesn't need to know how it's specialness is implemented just that its behaviour is unlike that of any other function.

Steve