Defining new functions in Arduino

ArduinoArduino BoardsArduino IDEArduino Programming Language

Defining new functions in Arduino is equivalent to defining the functions in C.

The syntax is −

Syntax

return_type function_name(arg_type arg)

The only difference is that in C, the function needs to be declared at the top, if it is invoked before its definition. No such constraint exists in Arduino. The following code demonstrates this −

Example

void setup() {
   Serial.begin(9600);
   Serial.println();
}
void loop() {
   // put your main code here, to run repeatedly:
   for (int i = 0; i < 10; i++) {
      long int w = square(i);
      Serial.println(w);
      delay(1000);
   }
}
long int square(int a) {
   return (a * a);
}

The Serial Monitor output is shown below −

Output

As you can see, even though the function was invoked before being defined, Arduino did not throw up an error. The execution worked just as expected.

raja
Published on 24-Mar-2021 05:26:20
Advertisements