Thuta Learning
C++
IntermediateProgrammingBeginner

Functions

C++Lesson 1235 min

What you'll walk away with

  • Write functions with a return type, name and parameter list, and tell void functions from value-returning ones
  • Decide between passing by value, by const reference and by non-const reference
  • Add default arguments in the right place and in the right order
  • Write overloaded functions and avoid ambiguous calls
  • Use a function prototype before main and check every return path

Explain it simply

Explain it simply

A function is a piece of code you give a name to, so a task can be written once and used anywhere by calling that name. Think of a coffee machine: put in water and coffee, and a cup comes out, with no need to know what happens inside.

In C++ every function states its signature: which type it gives back (the return type), its name, and what it accepts (the parameters). Parameters are the function's inputs and the return value is its output. A function that only does something and has nothing to give back is void. This lesson covers what learners must watch for: the difference between handing over a copy of an argument and handing over the original, the order of declarations, and how the compiler picks between functions with the same name.

Problem → Why → Solution

The problem: a discount function that changes nothing

A shop program lowers the price of a 2000-kyat item by 10 percent with applyDiscount(). The calculation inside the function is correct, and the compiler shows no warning even with -Wall -Wextra. Yet after the call, printing the price still shows 2000. The function did its work; it just changed nothing the caller can see.

discount_bug.cpp
#include <iostream>

void applyDiscount(double price, double percent) {
    price = price - price * percent / 100;   // 1800, but only inside here
}

int main() {
    double price = 2000;
    applyDiscount(price, 10);
    std::cout << "Price: " << price << '\n';   // Price: 2000
    return 0;
}

Why did nobody receive the 1800?

C++ passes arguments by copy by default (pass by value). The price inside applyDiscount() is a brand-new variable that merely shares a name with the one in main; the call copied 2000 into it. The function changed that copy to 1800 and then threw it away when it finished. To change the caller's variable, declare the parameter as a reference such as double&, or return the result and let the caller store it.

Core concept: the signature, copies and references

A function definition has a return type, a name, a parameter list in parentheses and a body in braces. The return statement sends a value back to the caller and ends the function at once. In a void function you may write a bare return; (or simply reach the closing brace). Every path of a value-returning function must end in a return, or the behaviour is undefined; main alone is special, because the compiler inserts return 0 for it.

The compiler reads a file from top to bottom, so a function must be declared before it is called. There are two fixes: put the definition above main, or write a prototype, a declaration with no body such as int square(int n);, above main and place the definition later. A prototype lets you keep main at the top, which often makes the file easier to read.

There are three ways to pass a parameter, and you choose one for each when you write the function. By value (int n) hands over a copy, which is simple and fast for small types such as int, double, char and bool. A const reference (const std::string& text) hands over the original for reading only, without copying, which is best for larger types like std::string when you only need to read. A non-const reference (double& price) lets the function modify the caller's variable directly. Marking a reference const when you do not modify it also tells the reader that the function makes no changes.

A default argument makes a parameter optional: with int times = 2, the caller may leave times out. Defaults must sit on the trailing parameters (every parameter after one with a default also needs a default), and they are written in exactly one place, either the prototype or the definition. Overloading lets you write several functions with the same name but different parameter types, and the compiler picks the one that matches the argument types. A difference in return type alone is not an overload, and when two overloads fit equally badly the call is ambiguous and does not compile.

Passing styleDeclarationUse it when
By valueint nthe type is small and copying is cheap
Const referenceconst std::string& syou only read a larger type
Referencedouble& priceyou must modify the caller's variable
Mental model: how a call runs
  1. Caller evaluates the arguments
  2. Parameters are initialised from them
  3. Body runs with its own locals
  4. return hands one value back

By value, the function holds a copy and cannot touch the caller's variable; only a reference reaches the original.

General pattern

cpp
ReturnType name(Type value, const BigType& readOnly);    // prototype

ReturnType name(Type value, const BigType& readOnly) {   // definition
    // body
    return result;                                       // none for void
}

void change(Type& target);                  // modifies the caller's object
ReturnType name(Type value, Type extra = defaultValue);  // optional extra
ReturnType name(OtherType value);           // overload: different parameters

A prototype ends with a semicolon and has no body, while the definition has one; the first can sit above main. The parameter type decides how arguments are passed: Type for a copy, const Type& for read-only access, Type& for modification. Write a default argument in one place only, and overloads must differ in their parameters.

Example: three kinds of function and one call each

This program has three functions: a void function that only prints, a function that returns an int, and a function that returns a double. The definitions sit above main, so the compiler knows them before it reaches main. Follow each call in main and track its result.

functions.cpp
#include <iostream>
#include <string>

void showWelcome(const std::string& name) {
    std::cout << "Welcome to the C++ lesson, " << name << "!\n";
}

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

double average(int total, int count) {
    return static_cast<double>(total) / count;
}

int main() {
    showWelcome("Aye");
    int total = add(5, 3);
    std::cout << "Total: " << total << '\n';
    std::cout << "Average of 2 numbers: " << average(total, 2) << '\n';
    return 0;
}

Code breakdown

  1. A void functionvoid showWelcome(const std::string& name) {

    void says this function returns no value; its whole job is to print. const std::string& name is a parameter that reads the caller's string without copying it and without being able to change it.

  2. Returning an intint add(int a, int b) {

    It accepts two ints and returns an int. a and b are by value, so they are copies of what the caller sent; even changing them in the body would not affect the caller.

  3. Converting before dividingreturn static_cast<double>(total) / count;

    The return type is double, but total and count are ints. Converting total first makes the division happen in floating point, giving 4 for 8 / 2 and 2.5 for 5 / 2. This avoids the integer-division trap from the operators lesson.

  4. Storing a resultint total = add(5, 3);

    The arguments 5 and 3 are copied into a and b, and add returns 8. The call expression itself has the value 8, which is why it can be stored in total.

  5. A call as a statementshowWelcome("Aye");

    A void function has no result to store, so the call is written as a statement on its own. The literal "Aye" is turned into a temporary std::string automatically so it can bind to the const std::string& parameter.

You should see
Welcome to the C++ lesson, Aye!
Total: 8
Average of 2 numbers: 4
What happens on add(5, 3)
  1. main calls add(5, 3)
  2. a = 5, b = 3 (copies)
  3. return a + b sends back 8
  4. main stores 8 in total

Prototypes and default arguments

In this snippet main is at the top and repeat() is announced by a prototype. The default values (times = 2 and separator = " ") are written in the prototype only, not repeated in the definition that follows. The caller may pass one, two or three arguments, which are matched to the parameters from the left, and the defaults fill in the rest.

repeat.cpp
#include <iostream>
#include <string>

std::string repeat(const std::string& text, int times = 2,
                   const std::string& separator = " ");

int main() {
    std::cout << repeat("ha") << '\n';
    std::cout << repeat("ha", 3) << '\n';
    std::cout << repeat("ha", 3, "-") << '\n';
    return 0;
}

std::string repeat(const std::string& text, int times, const std::string& separator) {
    std::string result;
    for (int i = 0; i < times; ++i) {
        if (i > 0) {
            result += separator;
        }
        result += text;
    }
    return result;
}

The output is ha ha, ha ha ha and ha-ha-ha. Repeating a default in the definition as well is an error: default argument given for parameter 2 of ... [-fpermissive], and placing a parameter without a default after one that has a default gives error: default argument missing for parameter 2 ....

Overloading: same name, different parameters

Overloading lets one operation be called by one name for data of different types. The compiler looks at the argument types and picks the best-matching overload at compile time, so there is no cost at run time. The literal 42 is an int, 4.2 is a double, and the string literal "forty-two" is converted to match const std::string&.

describe.cpp
#include <iostream>
#include <string>

void describe(int value) { std::cout << "int: " << value << '\n'; }
void describe(double value) { std::cout << "double: " << value << '\n'; }
void describe(const std::string& value) { std::cout << "string: " << value << '\n'; }

int main() {
    describe(42);
    describe(4.2);
    describe("forty-two");
    return 0;
}

A call that fits no overload best is ambiguous

With int add(int, int) and double add(double, double), the call add(5, 2.5) does not compile: error: call of overloaded 'add(int, double)' is ambiguous. The first overload fits the first argument better and the second fits the second argument better, so the compiler cannot choose. Convert one argument with static_cast, or add another overload.

Copy, const reference and reference side by side

This snippet runs two discount functions on the same price variable. The first modifies a copy, so price stays 2000, while the second uses double& and changes the caller's variable to 1800 directly. countVowels() only needs to read its text, so it takes a const std::string& and never copies the whole string.

passing.cpp
#include <iostream>
#include <string>

void discountCopy(double price, double percent) {
    price -= price * percent / 100;
}

void discountInPlace(double& price, double percent) {
    price -= price * percent / 100;
}

std::size_t countVowels(const std::string& text) {
    std::size_t count = 0;
    for (char c : text) {
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
            ++count;
        }
    }
    return count;
}

int main() {
    double price = 2000;
    discountCopy(price, 10);
    std::cout << "After discountCopy: " << price << '\n';
    discountInPlace(price, 10);
    std::cout << "After discountInPlace: " << price << '\n';
    std::cout << "Vowels: " << countVowels("mingalaba") << '\n';
    return 0;
}

The output is After discountCopy: 2000, After discountInPlace: 1800 and Vowels: 4. A function that silently changes its argument is often harder to read than one that returns its result, so reach for a reference parameter only when modifying the caller's object is the point.

In real projects

Where this shows up in real projects

Real projects split a program into short functions, each doing one job. In larger code bases the functions are declared as prototypes in header files (.h or .hpp) and defined in source files (.cpp), so other files include only the signature and can call the function without seeing how it is written. Changing one file does not force every file to be recompiled, which keeps builds fast.

The standard library itself uses overloading heavily: std::to_string has overloads for int, double and other types, and std::abs and std::max work the same way. Good APIs accept large objects as const& and use default arguments so callers only supply what they care about, for example log(message, level = Info). Short, well-named functions are also easy to test, because you can check their inputs and outputs directly.

Common mistakes

Common mistakes

1. Forgetting a return on one path

In int grade(int mark) { if (mark >= 50) { return 1; } }, a mark below 50 lets the function finish without returning anything, which is undefined behaviour. g++ -Wall says warning: control reaches end of non-void function [-Wreturn-type], but the code still compiles, so the warning is easy to miss. Return on every path, and consider turning on -Werror=return-type.

2. Expecting a by-value parameter to change the caller

void applyDiscount(double price, ...) only changes its copy, so the caller's price stays the same, and the compiler says nothing. Declare double& price to modify the caller's variable, or return the double instead. When you do not modify an argument, taking larger types by const& avoids needless copies.

3. Calling a function before it is declared

If main calls square(3) but square is defined below main, g++ reports error: 'square' was not declared in this scope. The compiler reads from top to bottom and has not met square at the point of the call. Add the prototype int square(int n); above main, or move the definition up.

4. Writing a call that is ambiguous between overloads

With int add(int, int) and double add(double, double), calling add(5, 2.5) fails with error: call of overloaded 'add(int, double)' is ambiguous. Pass arguments whose types match one overload (add(5.0, 2.5)) or use an explicit cast.

Best practices

Best practices

  • Give each function one job and a name that describes it, such as calculateTotal.
  • Pass small types by value and larger read-only types by const&, and use a non-const reference only when modification is the point.
  • Prefer returning a result over changing it through a reference parameter when that reads more clearly.
  • Compile with -Wall -Wextra and treat a missing-return warning as an error.

Mini challenge

Mini challenge: receipt helpers

Write four functions for a shop receipt and combine them in main, practising a default argument, a const reference, a non-const reference and an overload.

  • lineTotal(unitPrice, quantity): quantity defaults to 1
  • label(name, quantity): takes name as const std::string& and returns a string such as "Tea x3"
  • applyCoupon(total, percent): takes total by reference and lowers the caller's variable by percent
  • Write two overloads of printAmount, one for int and one for double
receipt.cpp
#include <iostream>
#include <string>

// TODO: int lineTotal(int unitPrice, ...)      quantity defaults to 1
// TODO: std::string label(...)                 name by const reference
// TODO: void applyCoupon(...)                  total by reference
// TODO: void printAmount(int ...) and void printAmount(double ...)

int main() {
    // TODO: tea: 1500 Ks x 3, biscuits: 800 Ks (default quantity)
    // TODO: print the label and line total of the tea
    // TODO: sum both lines, apply a 10 percent coupon, print the total
    // TODO: print 2.5 with the double overload
    return 0;
}

Expected: The output should be: Tea x3: 4500 Ks Total after coupon: 4770 Ks Half portion: 2.5 Ks

Show hint

Put the default argument last in the parameter list (int quantity = 1). Use std::to_string to turn the number into text, as in name + " x" + std::to_string(quantity); it lives in <string>. Inside applyCoupon, write total -= total * percent / 100;.

Show solution
receipt.cpp
#include <iostream>
#include <string>

int lineTotal(int unitPrice, int quantity = 1) {
    return unitPrice * quantity;
}

std::string label(const std::string& name, int quantity) {
    return name + " x" + std::to_string(quantity);
}

void applyCoupon(int& total, int percent) {
    total -= total * percent / 100;
}

void printAmount(int ks) {
    std::cout << ks << " Ks\n";
}

void printAmount(double ks) {
    std::cout << ks << " Ks\n";
}

int main() {
    int tea = lineTotal(1500, 3);
    int biscuits = lineTotal(800);
    std::cout << label("Tea", 3) << ": " << tea << " Ks\n";

    int total = tea + biscuits;
    applyCoupon(total, 10);
    std::cout << "Total after coupon: ";
    printAmount(total);

    std::cout << "Half portion: ";
    printAmount(2.5);
    return 0;
}

Quick quiz 1 / 3

What does this print? void bump(int n) { n++; std::cout << n << ' '; } int main() { int x = 5; bump(x); std::cout << x; }

Quick quiz 2 / 3

Which prototype fails to compile?

Quick quiz 3 / 3

With both int add(int, int) and double add(double, double) declared, what does add(5, 2.5) do?

What to remember

  • A function has a return type, a name, a parameter list and a body, and return sends a value back and ends the function.
  • The compiler reads top to bottom, so declare before use: put the definition above, or add a prototype.
  • Arguments are copied by default; use const& for read-only access and a non-const reference to modify.
  • Default arguments sit on trailing parameters in one place only, and overloads must differ in parameter types.
  • Check every return path, and compile with -Wall -Wextra.

The Current ISO C++ Standard (C++23) — Standard C++ Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Functions | Thuta Learning