References and Mutation
Lesson 18 of 48 in Coddy's C++ for Lua Developers course.
Lua passes every argument by value, but a table value is a reference to the table. Assigning to a parameter inside a function never changes the caller's variable, while changing a field of a table argument is visible to the caller. There is no way to pass a local number by reference; you return the new value or wrap it in a table. A C++ reference is another name for an existing object. A non-const reference parameter such as int& lets the function change the caller's variable directly, a const reference lets it read without copying, and a reference can never be rebound once initialized.
Lua
local function bump(value, box)
value = value + 3
box.n = box.n + 3
end
local n = 4
local box = {n = 4}
bump(n, box)
print(n)
print(box.n)
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
int bump(int value,int& target){
value+=3;
target+=3;
return value;
}
int main(){
int a=4,b=4;
bump(a,b);
int& alias=a;
alias+=10;
std::cout<<a<<" "<<b<<"\n";
}
When a Lua function mutates a table it was given, the C++ port usually takes a non-const reference. When it only reads, take a const reference instead of copying.
Challenge
EasyInput: two integers. Exchange their values through reference parameters. Driver prints the mutated caller variables.
Implement the declared API in exercise.hpp and exercise.cpp. Both files are editable; preserve the public signatures. The locked main.cpp reads stdin and calls the API directly. It also checks public API behavior independently where stated. Return values rather than printing inside the API. Integer inputs and results fit signed int; text is ASCII unless stated otherwise.
Try it yourself
#include "exercise.hpp"
#include <iostream>
int main(){
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int a,b;in>>a>>b;exchange(a,b);std::cout<<a<<" "<<b<<"\n";
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in C++ for Lua Developers
1C++ Files and Values
Run the C++ FilesStrings and OutputTypes and InitializationDivision and RemaindersBooleans and ConditionsRecap: Parcel Charges4Copies and Algorithms
Value CopiesReferences and MutationFilter and TransformSorting with ComparatorsRecap: Top Unique Scores2Conditions and Iteration
Text EqualityBranches and RangesCounted IterationEarly Exit and SkippingRecap: Ticket Bands5Functions and Templates
Functions and ReturnsOverloads and DefaultsLambdas and CapturesFunction TemplatesRecap: Tiered Discounts8Composition and Ownership
Composition by ValueVirtual DispatchAbstract Base ContractsMove-only OwnershipRecap: Polymorphic Prices3Standard Containers
Fixed-size ArraysGrowing VectorsMaps and LookupSets and MembershipRecap: Shared Tags6Parsing and Lifetime
Streams and Exact ParsingExceptions and ContractsHeaders and LinkageRAII and Scope ExitRecap: Validate Lines9Project: Library Desk
Project: Book StockProject: Loan FeesPractice on your own: Online C++ compiler