C++•Functions
C++ Functions: Pass-by-Value, Pass-by-Reference, and Const
Learn function declarations, pass-by-reference for performance and mutation, and default parameter values.
Syntax
return_type function_name(const Type& param) {
return val;
}
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| Type& param | Reference | Passes alias to original argument, allowing in-place mutation without copy. |
| const Type& param | Const Reference | Zero-copy read-only access (best practice for objects). |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C++ locally:
#include <iostream>
#include <string>
// 1. Pass by reference (mutates original)
void swapNumbers(int& x, int& y) {
int temp = x;
x = y;
y = temp;
}
// 2. Pass by const reference (zero-copy, read-only)
void displayBanner(const std::string& title) {
std::cout << "=== " << title << " ===\n";
}
int main() {
int a = 10, b = 99;
std::cout << "Before swap: a=" << a << ", b=" << b << "\n";
swapNumbers(a, b);
std::cout << "After swap: a=" << a << ", b=" << b << "\n\n";
displayBanner("Compilra C++ Workspace");
return 0;
}Expected Output:
Before swap: a=10, b=99 After swap: a=99, b=10 === Compilra C++ Workspace ===
How It Works: Step-by-Step
- Lines 5-9: Passes integers by reference (&) to swap in place without pointers.
- Lines 12-14: Accepts string by const reference (&) to avoid copying heap buffer.
Key Concepts
- Pass by value for cheap primitives (int, double, char).
- Pass by const reference (const Type&) for non-trivial types (std::string, std::vector).
- Pass by non-const reference (Type&) only when the function is intended to mutate the argument.
Common Mistake: Passing large containers or strings by value
Passing void process(std::vector<int> v) copies the entire vector buffer into function stack.
❌ Incorrect
void printData(std::vector<int> data) { /* Incurs full heap allocation copy! */ }✅ Correct
void printData(const std::vector<int>& data) { /* Zero copy overhead */ }Related C++ Tutorials & Compiler
C++ Pointers and References: Memory Addresses Explained
Master memory addresses, pointer dereferencing (*), address-of operator (&), and references.
C++ Classes and Object-Oriented Programming (OOP)
Construct object blueprints with public/private access specifiers, constructors, and destructors.
C++ Exception Handling: try, catch, and std::exception
Catch and throw runtime exceptions safely using try, catch, and standard library exceptions.
C++ Online Compiler
Open in Compilra IDE
Run and test C++ on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.