Sub topic 12
Parameters and return values
This chapter assumes you can write a sketch with setup() and loop(), declare variables, use for loops, and define a simple function with no inputs. It builds on the previous chapter by showing how a function receives data and sends a result back. It also covers the errors that most often appear when you do this on a small board such as the Uno.
Why functions need inputs and outputs
A function with no inputs and no output can only act on global variables. That works for tiny sketches, but it ties the function to one specific pin or variable. Parameters and return values remove that tie. A function takes what it needs as input and hands back what it computed, and the caller decides what to do with the result.
- A parameter is a variable declared in the function's parentheses. It receives a value when the function is called.
- An argument is the actual value you pass in at the call site.
- A return value is the single value a function sends back to its caller with
return.
int readAverage(int pin, byte samples) {
long total = 0;
for (byte i = 0; i < samples; i++) {
total += analogRead(pin);
delay(2);
}
return total / samples;
}
void setup() {
Serial.begin(9600);
}
void loop() {
int average = readAverage(A0, 10);
Serial.println(average);
delay(500);
}In this sketch, pin and samples are parameters. In the call readAverage(A0, 10), the values A0 and 10 are the arguments. The function returns an int, and loop() stores it in average.
Anatomy of a function definition
A definition has four parts: the return type, the name, the parameter list, and the body.
int readAverage(int pin, byte samples) {
// body
}intis the return type. The function must return a value of this type, or one that converts to it.readAverageis the name. Pick a verb phrase that says what the function does.(int pin, byte samples)is the parameter list. Each parameter needs its own type. Writing(int pin, samples)is a compile error.- The body runs when the function is called.
A function that returns nothing has the return type void. setup() and loop() are both void functions with empty parameter lists.
How the call works
When you call a function, the compiler copies each argument into the matching parameter, in order. The function runs, and return copies a value back to the caller.
The diagram below shows the order of events for one call.
The values of pin and samples exist only while the function runs. This follows the scope rules from the earlier chapter: parameters are local variables. They are created on each call and discarded when the function returns.
Pass by value
By default, C++ passes arguments by value. The function gets a copy, so changing a parameter does not change the caller's variable.
void addOne(int n) {
n = n + 1;
Serial.print("Inside: ");
Serial.println(n);
}
void setup() {
Serial.begin(9600);
int x = 5;
addOne(x);
Serial.print("Outside: ");
Serial.println(x);
}
void loop() {}This prints Inside: 6 and then Outside: 5. The function changed only its copy.
This is usually what you want, because a function cannot accidentally damage the caller's data. For small types such as int, byte, and bool, copying is as cheap as anything else on an AVR board.
Pass by reference
If you want a function to modify the caller's variable, declare the parameter as a reference by adding &.
void addOne(int &n) {
n = n + 1;
}
void setup() {
Serial.begin(9600);
int x = 5;
addOne(x);
Serial.println(x);
}
void loop() {}This prints 6. The parameter n is another name for x, not a copy.
References are also the usual way to return more than one result, because a function can only return one value.
void splitSeconds(unsigned long total, byte &minutes, byte &seconds) {
minutes = total / 60;
seconds = total % 60;
}
void setup() {
Serial.begin(9600);
byte m, s;
splitSeconds(135, m, s);
Serial.print(m);
Serial.print(":");
Serial.println(s);
}
void loop() {}This prints 2:15.
<br>
Return values in detail
Returning from the middle of a function
return ends the function at once. You can use it to leave early when a condition is not met.
int safeDivide(int a, int b) {
if (b == 0) {
return 0; // avoid dividing by zero
}
return a / b;
}Every path through a non-void function should reach a return. If one does not, the result is undefined. The compiler may warn you, but not always, so check this by reading the code.
Returning bool for yes/no questions
Functions that answer a question are easier to read when they return bool, and when their names read like a question.
bool isButtonPressed(byte pin) {
return digitalRead(pin) == LOW; // wired with INPUT_PULLUP
}
void loop() {
if (isButtonPressed(2)) {
digitalWrite(LED_BUILTIN, HIGH);
}
}The condition if (isButtonPressed(2)) reads almost like a sentence, and the wiring detail stays in one place.
Ignoring a return value
You can call a function and discard what it returns. Serial.print() itself returns the number of bytes written, and most sketches ignore it. Be careful with functions where the result matters, for example Serial.available() or digitalRead(). Calling them without using the result does nothing useful.
Choosing types for parameters and results
The type you choose controls both the range of values and the memory used. The Uno has 2 KB of RAM, so these choices matter more than on a PC.
| Situation | Suggested type | Reason |
|---|---|---|
| Pin numbers | `byte` or `int` | Pins on an Uno are 0 to 19, so a `byte` is enough. |
| `analogRead()` result | `int` | Values range from 0 to 1023. |
| Sum of many readings | `long` | Ten readings of 1023 reach 10230, which fits in an `int`, but 100 readings reach 102300, which overflows a 16-bit `int`. |
| Time from `millis()` | `unsigned long` | It is a 32-bit unsigned value. |
| True/false result | `bool` | It states the intent. |
The readAverage() function uses long total for exactly this reason. With an int accumulator, a larger sample count would overflow and give a wrong average with no error message.
Integer division and implicit conversion
When both operands are integers, / discards the fractional part. In readAverage(), total / samples gives a whole number. If you need a fraction, convert one operand first.
float averageVoltage(int pin, byte samples) {
long total = 0;
for (byte i = 0; i < samples; i++) {
total += analogRead(pin);
}
float average = (float)total / samples;
return average * 5.0 / 1023.0;
}Without the (float) cast, total / samples would be computed as an integer first, and the fraction would already be lost.
Default arguments
C++ lets you give a parameter a default value, so callers can leave it out.
int readAverage(int pin, byte samples = 8) {
long total = 0;
for (byte i = 0; i < samples; i++) {
total += analogRead(pin);
delay(2);
}
return total / samples;
}
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println(readAverage(A0)); // uses 8 samples
Serial.println(readAverage(A0, 20)); // uses 20 samples
delay(500);
}Defaults must come last in the parameter list. A default in the middle is a compile error.
Overloading
Two functions can share a name if their parameter lists differ. The compiler chooses by the argument types.
void show(int value) {
Serial.print("int: ");
Serial.println(value);
}
void show(float value) {
Serial.print("float: ");
Serial.println(value, 2);
}
void setup() {
Serial.begin(9600);
show(42);
show(3.14159);
}
void loop() {}Overloading on the return type alone is not allowed. Keep overloads rare in beginner sketches, because they can make errors harder to read.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `'x' was not declared in this scope` inside a function | The function uses a local variable of the caller. | Pass it as a parameter. |
| The caller's variable does not change | Passed by value. | Use a reference parameter or return the new value. |
| Wrong average or negative totals | Accumulator type too small. | Use `long` for sums. |
| Result is always a whole number | Integer division. | Cast one operand to `float`. |
| Garbage returned from a function | A path with no `return`. | Make every path return a value. |
| `too few arguments to function` | Call does not match the definition. | Match the number and order of arguments. |
Two other mistakes deserve a closer look.
- Swapped arguments.
readAverage(10, A0)compiles, because both are numbers. The function then reads pin 10 with 14 samples, andA0is 14 on an Uno. The compiler cannot catch this. Use clear parameter names and keep to a consistent order across your functions. - Returning the address of a local variable. Locals vanish when the function returns. Returning a pointer or reference to one gives a dangling value. Return the value itself instead.
Arrays as parameters
An array parameter does not copy the array. The function receives the address of its first element, and it cannot tell how long the array is. Pass the length separately.
int largest(const int values[], byte count) {
int best = values[0];
for (byte i = 1; i < count; i++) {
if (values[i] > best) {
best = values[i];
}
}
return best;
}
const int readings[] = {120, 530, 87, 910, 402};
void setup() {
Serial.begin(9600);
byte count = sizeof(readings) / sizeof(readings[0]);
Serial.println(largest(readings, count));
}
void loop() {}This prints 910. Marking the parameter const promises that the function will not modify the array, and the compiler enforces that promise. Because arrays are not copied, a function can change the caller's array unless you use const.
The sizeof calculation must happen where the array is declared. Inside largest(), sizeof(values) would give the size of a pointer, not the array.
Putting it together
The sketch below combines parameters, a return value, a bool helper, and a static variable from the earlier scope chapter. It reads a sensor, decides whether the value is above a threshold, and counts how many times that happened.
const byte sensorPin = A0;
const byte ledPin = 8;
int readAverage(int pin, byte samples = 8) {
long total = 0;
for (byte i = 0; i < samples; i++) {
total += analogRead(pin);
delay(2);
}
return total / samples;
}
bool isAbove(int value, int threshold) {
return value > threshold;
}
unsigned int countEvents(bool eventHappened) {
static unsigned int events = 0;
if (eventHappened) {
events++;
}
return events;
}
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
int level = readAverage(sensorPin);
bool high = isAbove(level, 600);
digitalWrite(ledPin, high ? HIGH : LOW);
Serial.print("Level: ");
Serial.print(level);
Serial.print(" Events: ");
Serial.println(countEvents(high));
delay(250);
}Each function does one job and has a clear input and output. The decision logic in isAbove() can change without touching the code that reads the sensor.
Exercises
Exercise
What does this sketch print, and why? void change(int n) { n = 10; } void setup() { Serial.begin(9600); int x = 3; change(x); Serial.println(x); } void loop() {}
Show answer
It prints 3. The parameter n is a copy of x, so assigning 10 to n does not affect x. To change x, declare the parameter as a reference with int &n.
Exercise
Write a function named clampValue that takes an int value, an int low, and an int high, and returns value limited to the range from low to high. Then explain why it should return a value instead of printing it.
Show answer
int clampValue(int value, int low, int high) { if (value < low) { return low; } if (value > high) { return high; } return value; } Returning the value lets the caller decide what to do with it: print it, compare it, or send it to a pin with analogWrite(). A function that prints is limited to one use and needs the Serial port to be started.
Exercise
A function sums 200 analogRead() results into an int and then divides by 200. The average is wrong and sometimes negative. What is the cause, and how do you fix it?
Show answer
The sum can reach 200 x 1023 = 204600, which exceeds the 16-bit int limit of 32767 on an Uno, so it overflows. Declare the accumulator as long (or unsigned long) and divide after summing.