What is different between the following?
(1)
void function1()
void function2()
...
void setup()
void loop()
or
(2)
void setup()
void loop()
void function1()
void function2()
...
What is different between the following?
(1)
void function1()
void function2()
...
void setup()
void loop()
or
(2)
void setup()
void loop()
void function1()
void function2()
...
As far as functionality in the Arduino environment there is no difference
In a more general C++ environment, functions have to be defined before they can be used so option 2 would not work if function1() or function2() were called from setup() or loop()
The Arduino environment gets round this requirement by adding the function prototypes for you at the start of the sketch as part of the compilation process but you do not see this
I see what you mean, but more precisely functions have to be declared before they can be used. They can be defined later.
That's what the IDE does, it declares the function at the top of the code (by adding the function prototypes as you said) and then the compiler is fine, it knows what are the parameters, the returned value and the name of the function.
I start doing functions that control the hardware. Then I start the main code. As I am going I will need a function I will write a dummy with a note as to what is passed, expected to do and return.Then when I have the bulk of the code done I go back and fill in the functions and funny thing as the code was written the functions grew in capability and number.
I have a function library so most of the time writing functions is not needed, just reference them to be sure they are called correctly. Just like my ASM days.
Thanks @J-M-L
One day I will remember the difference between declaration and definition
In some sketches I separate functions into header files (functionname.h) and including the header files in the main sketch. This avoids searching hundreds of lines in one file when debugging, and a clean main sketch.
#include <function1.h>
// #include <function2.h> // function not used
#include <function3.h>
As mentioned, little difference.
Personally, I prefer option #2, however, sometimes place functions in a separate tab.
But Iām a hardware kind of guy
That's my preferred method as well. With many functions for different tasks, there can be multiple tabs with FunctionsForThis and FunctionsForThat, etc.