New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› C++› Functions and Parameters

Functions and Parameters

💻 C++

Break programs into functions and understand pass-by-value and pass-by-reference.

Lesson 4 of 9 Tutorial
0 of 9 completed

Functions make code reusable and testable. In C++ you also control whether a parameter is copied or referenced.

By the end of this lesson you can:
  • Define and call functions.
  • Use pass-by-reference.
  • Provide default arguments.

A Function

Declare the return type, name and parameter types. A function must be declared before it is called.

#include <iostream>

int add(int a, int b) {
    return a + b;
}

void greet(const std::string& name) {
    std::cout << "Hello, " << name << "\n";
}

int main() {
    std::cout << add(3, 4) << "\n";
    greet("Amina");
    return 0;
}

Pass by Reference

By default, arguments are copied. For large objects, pass by const reference to avoid the copy. Use a non-const reference when the function must change the caller's value.

void addScore(int& score, int points) {
    score += points;
}

int score = 60;
addScore(score, 10); // score is now 70

Default Arguments

A parameter can have a default value. Defaults must come after parameters without defaults.

double priceWithVat(double price, double rate = 0.075) {
    return price * (1 + rate);
}
Tip Mark functions that do not change their parameters as const references. It documents intent and avoids accidental copies.

Practice

  1. Write a function that returns the larger of two numbers.
  2. Write a function that doubles a number through a reference.
  3. Add a default argument to a greeting function.

Hands-on exercise

Write two functions:
1. char grade(int score) returning A to F.
2. double average(const std::vector<int>& scores).
Print the grade and average for three scores.

Recap

Functions name work. Pass small values by value and large or mutable values by reference.

Example

#include <iostream>

int add(int a, int b) {
    return a + b;
}

void greet(const std::string& name) {
    std::cout << "Hello, " << name << "
";
}

int main() {
    std::cout << add(3, 4) << "
";
    greet("Amina");
    return 0;
}

Exercises

Exercise 1. Grade and average Medium
Write two functions:
1. char grade(int score) returning A to F.
2. double average(const std::vector<int>& scores).
Print the grade and average for three scores.
C++ exercise-1.txt
Expected Output
Grade B and Average 74.6667

Lesson Nav

Lesson sections