Syntax order question

After reviewing a bunch of the sample code for Arduino, I notice that in some examples functions after the loop() function are created that run inside the loop() function.

In this code example: http://arduino.cc/en/Tutorial/ShftOut12

The lightShiftPinA(), lightShiftPinB() and blinkAll() functions, which are called in the loop() function, are all wrote after the loop() function.

Is this standard procedure with C++ and is there an advantage to writing scripts this way? I come from writing php (object oriented) and have not been exposed to coding this way. Although the syntax is very similar between the two languages, I'm sort of puzzled why a script would be wrote in a reverse order. My inclination would be to put those functions before the loop function. There must be a reason it was wrote this way though.

Can someone shed some light on this for me? Thanks!

You can do this in C, C++, and PHP, AFAIK.

Really, its just historical convention. Put them where you like, or where you feel most comfortable. I am not sure why or how this started, but I have stated before here that I think it might have been an artifact of single vs multiple-pass compilers (ie, before multi-pass compilers, you had to define all of the functions before the main() function, so that the compiler already had a list of addresses for use by calls in main()...), but I am not really sure.

:slight_smile:

Also - just in case you aren't aware; there is a main() function used by the Arduino, that looks something like this:

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

I am not sure if you can change it or re-define it in some fashion (not sure where in the process it is added/performed/etc) - but I know I have seen some discussion on it either here in the forums and/or on the arduino.cc site.

Just a little tidbit that you may or may not have known about (and really, it doesn't affect much except a bit of overhead for the call to the loop() function).

:slight_smile:

I think it might have been an artifact of single vs multiple-pass compilers

Naw. Years ago there was a big debate about "top down design" versus "bottom up design". Not too different from "Extreme Programming" versus everything else.

The "top down" folks thought main should be first with big steps. The further down the source file, the more detailed the functions.

The "bottom up" folks thought one should start with the most detailed stuff working towards the big picture. Which puts main consistently at the bottom of the source file.

I think it's a whole lot of manure. Whether you go "top down" or "bottom up" you always end up upside down. Do what works best for you.

I learn something new every day!

:slight_smile:

Interesting. Thanks for the answers.