Other than in ordinary C / C++ , the Arduino IDE allows to call a function before it is defined.
In .cpp files, you have to define the function, or at least declare the function prototype before you can use it.
In an .ino file, the Arduino IDE creates such a prototype behind the scenes.
int squareNum (int a) {
return a*a;
}
int
: return type
squareNum
: function name
int a
: parameter type and name
return a*a
: return a value (same type as the return type defined at the beginning)
If you have a function declared you can call it anywhere else in the code. Here is an example of calling a function:
void setup(){
Serial.begin(9600);
}
void loop() {
int i = 2;
int k = squareNum(i); // k now contains 4
Serial.println(k);
delay(500);
}
int squareNum(int a) {
return a*a;
}