Declaring Functions

I’ve been reading a book on C++ for beginners to try and get a better understanding of programming the Arduino and I am curious about declaring functions.

In the book it says that function prototypes need to be declared before you use a function.

In Arduino IDE, this doesn’t appear to be a requirement judging from examples that I have seen, however, if you do declare a function prototype, it doesn’t appear to cause any compiling errors.

Even if there is no requirement to declare function prototypes in Arduino IDE, is it considered good practice to do so anyway?

the book is right, the compiler needs to know what the function looks like before you can call it. You get there either by defining the function before you use it or just indeed put the declaration ahead and provide the implementation later.

The IDE is trying to be smart and will parse the .ino code and generate a .cpp file with the function's prototype for you before compiling, that's why you don't need to do that using the IDE.

My take on this is don't learn to depend on this feature of the IDE. That will come bite you sooner or later. it's not difficult to provide the function at the start of the sketch (or their declaration).

As you have discovered, when using the Arduino IDE it is not necessary to declare functions. The IDE does it for you as part of making using the Arduino environment easier to use

There is no harm in declaring functions if you want to and there are some rare instances where it is necessary. One such that I have seen is where optional parameters with default values are passed to a function

It seems that declaring functions may be a good habit to get into in case I want to use C++ on another platform.

declaring can be done at the same time you define the function.

What matters is that the code never uses something that is unknown (it needs to have been declared/defined earlier)

ie this is fine with an upfront declaration, so that printThis() is known in the setup

void printThis(int x);

void setup() {
  Serial.begin(115200);
  printThis(10);
}

void loop() {}

void printThis(int x) {
  Serial.print("x = "); Serial.println(x);
}

but you could do this too

void printThis(int x) {
  Serial.print("x = "); Serial.println(x);
}

void setup() {
  Serial.begin(115200);
  printThis(10);
}

void loop() {}

Now printThis() is fully defined (thus declared) before you call it and so it's fine too.

Yes!!! I always do so by using function prototypes that just tell the compiler the function's name, arguments, and return value. That allows you to place the function's implementation anywhere, not just before it's called.

Also, learning how to use function prototypes is critical for when you want to start breaking large programs into individual .h / .cpp files. Don't even both starting to use the "Arduino Method" of multiple .ino files.

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