Return Statement

I am looking over some OneWire code and I do not totally understand the use of the return statements. Here is a example:

void loop(void) {
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit; 

  if ( !ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(250);
    return;
  }

The program at the point it reaches the return statement is not in a subroutine other than loop(). So where does it return to? Does it gist restart the loop() code?

It causes an exit from loop(). Since loop() is called repeatedly, the effect is to re-start the loop() code from where it begins.

Thanks for clearing that up!

I never use that method. I would:

void loop(void) {
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit; 

  if ( !ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(250);
  }
  else
  { do the rest of the code in loop... }
}

return there is to skip the code that follows that you failed to show.

I consider myself to be a descent C programmer but Arduino does things a little different. I'm not sure why they ditched the main() sub to replace it with setup() and loop(). Thanks for the help.

I'm also at a loss. :slight_smile:

It does save having to explain what 'while(1)' means.

When the Arduino was started decades ago it was intended as a simple way to use micro-controllers for non programmers. I thought of it as micros for artisans and poets. Since then it has grown like a cancer and become much more complex

There in fact is a main() function (they're not called subroutines in C / C++). It's just hidden from easy viewing (but you can find it) in the Arduino world. Its job is to initialize some hardware, call the setup() function where you do one-time stuff, and then call the loop() function inside an endless loop.

Now consider for a moment what your own main() function would do if this Arduino setup/loop paradigm didn't exist. It would initialize some hardware, do some one-time stuff, and then it would continually execute your main code in an endless loop. Sound familiar? So, the setup/loop paradigm works the way you'd write it yourself for 99.999% of the use cases.

Yeah, it's painless and does the same thing. I don't sweat it too much.

Don't leave us in the dark. How do you find the main function?

It depends on the details of your Arduino installation. I use Portable Installations. So, for v1.8.15 of the IDE, 'main.cpp' is in 'D:\Arduino-1.8.15\hardware\arduino\avr\cores\arduino'

You are free to define your own main(), it will run instead