HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to C++VariablesData TypesOperatorsStringsVectors (vector)Conditions (if / switch)Loops (for / while)FunctionsClasses (OOP)
REFERENCE
📖 Overview
🖥️ Output & Input
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array & Vector
🔁 Condition & Loop
🧩 Function & Class
C++›Functions

Functions

Function definition, parameter/return types and parameter by reference (&).

Simple enough for a 5-year-old to understand

Functions and return

Example code
1
#include <iostream>
2
using namespace std;
3
int square(int x) {
Takes an int, returns an int.
FunctionTakes an int, returns an int.
4
return x * x;
5
}
6
int main() {
7
cout << square(5) << endl;
25
Output / Input25
8
return 0;
9
}
FunctionOutput / Input
💡 Hint: Functions are defined before main (otherwise a prototype is needed).

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Write a function named addUp that takes two ints and returns their sum; print addUp(8, 9).

🎯 Expected output: 17

Loading editor…

About this topic

In C++, functions are declared with return types and parameter types, just like in C. C++ adds three important features: overloading functions with the same name but different parameter lists, giving default values to parameters, and passing parameters by reference.

References make most pointer usage from C unnecessary. A reference to a variable is another name for that variable; you work on the original variable without writing asterisks and ampersands. There is also no possibility of being NULL.

There are three options for passing parameters, and the choice determines readability: value copies, reference gives the original variable, and const reference allows reading without copying. For reading large objects, const reference is the default choice.

What you will learn

  • Function definition and prototype
  • Passing by value, reference, and const reference
  • Defining multiple functions with the same name
  • Default parameter values
  • Why returning a local object is safe

When to use?

If you are passing a large object to a function for reading only, use a const reference: there is no copying cost and protection against modification is provided.

If the function needs to modify the caller's variable, use a reference; pointers are only needed when a value might be absent.

Common mistakes

Wrong

#include <iostream>
using namespace std;

void increase(int value) {
    value += 10;
}

int main() {
    int total = 5;
    increase(total);
    cout << total << endl;
    return 0;
}

Since the parameter is passed by value, the function works on a copy and total does not change; five is printed to the screen. There is no error message. To modify the caller's variable, you need to take by reference, and in C++, this is more readable than using a pointer.

Correct

#include <iostream>
using namespace std;

void increase(int &value) {
    value += 10;
}

int main() {
    int total = 5;
    increase(total);
    cout << total << endl;
    return 0;
}

Wrong

#include <iostream>
using namespace std;

int &getValue() {
    int local = 42;
    return local;
}

int main() {
    cout << getValue() << endl;
    return 0;
}

The local variable disappears when the function ends; returning a reference to it creates a dangling reference, and reading it is undefined behavior. The compiler gives the warning "reference to local variable returned". Returning a local object BY VALUE is safe and has no extra cost in modern C++.

Correct

#include <iostream>
using namespace std;

int getValue() {
    int local = 42;
    return local;
}

int main() {
    cout << getValue() << endl;
    return 0;
}

Wrong

#include <iostream>
using namespace std;

void greet(string name = "Guest", string title) {
    cout << title << " " << name << endl;
}

int main() {
    greet("Ali", "Dear");
    return 0;
}

A parameter without a default value cannot come after a parameter with a default value; the compiler gives a "default argument missing" error. The rule is a technical necessity: since missing arguments in a call are filled from the right, defaults must be on the far right.

Correct

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

void greet(string title, string name = "Guest") {
    cout << title << " " << name << endl;
}

int main() {
    greet("Dear", "Ali");
    return 0;
}

Frequently asked questions

How are two functions with the same name distinguished?

By the number and types of parameters; the compiler chooses the best match for the arguments in the call. Having only a different return type is not enough; this gives a compilation error. When multiple options have equal suitability, you also get an ambiguity error.

Which one should I choose between reference and pointer?

Reference whenever the value always exists. A reference cannot be NULL, cannot be reseated, and does not require writing stars. Pointers are needed when the absence of a value is meaningful or when the address will be reassigned.

Isn't returning a local object by value slow?

Not in modern C++. The compiler performs return value optimization and constructs the object directly at the target; no copy is created at all. This optimization is now mandated by the standard in certain cases.

Summary

Parameters are copied by default; to modify them, take by reference.

Const references are used to read large objects.

References to local variables are not returned; returning by value is safe.

Parameters with default values must be placed at the end of the list.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code