Parameters and Return Values

Parameters: giving the function information

A function becomes much more useful when you can give it values to work with. These are called parameters. Each one has a type and a name:

#include <iostream>
#include <string>
using namespace std;

void greet(string name, int age) {
    cout << "Hi " << name << ", you are " << age << "!\n";
}

int main() {
    greet("Maya", 12);
    greet("Leo", 30);
    return 0;
}

Output

Hi Maya, you are 12!
Hi Leo, you are 30!

The values you pass in the call ("Maya", 12) are called arguments. They are copied into the parameters in the same order.

return: giving a result back

Instead of void, write the type of value the function gives back. Then use return to send the result:

#include <iostream>
using namespace std;

int square(int x) {
    return x * x;
}

double average(double a, double b) {
    return (a + b) / 2;
}

int main() {
    int s = square(6);
    cout << "6 squared is " << s << "\n";
    cout << "Average of 3 and 8: " << average(3, 8) << "\n";
    cout << square(2) + square(3) << "\n";
    return 0;
}

Output

6 squared is 36
Average of 3 and 8: 5.5
13

Think of it like this: A function with a return value is like a vending machine. You put in money (arguments), and a snack comes back out (the return value) that you can use.

Functions that answer questions

A function that returns a bool makes your ifs very readable:

#include <iostream>
using namespace std;

bool isEven(int n) {
    return n % 2 == 0;
}

int main() {
    for (int i = 1; i <= 4; i++) {
        if (isEven(i)) {
            cout << i << " is even\n";
        } else {
            cout << i << " is odd\n";
        }
    }
    return 0;
}

Output

1 is odd
2 is even
3 is odd
4 is even

Remember: return ends the function immediately. Any code after it in the function does not run.

Common mistake: Forgetting to use the returned value. square(5); on its own calculates 25 and throws it away. Store it (int r = square(5);) or print it.

HOME LABS COMMUNITY DASHBOARD