CodeBlanks Logo Icon CodeBlanks

Summary - References

Combine reference, const reference and safety to write a swap function.

Summary - References

In this group you learned the core tools of references: declaring, reference parameters, const references, and the dangling reference danger. References are a key tool for writing safe and efficient code in C++.

There are two tasks. First, you will write a swap function with two reference parameters. Second, you will define a printSum function with a const std::vector<int>& parameter. Both combine what you have learned.

Practice The swap function

Define a void swap(int& a, int& b) function; in the body exchange a and b using an int t temporary variable. In main declare int x = 1, y = 2;, call swap(x, y), and print x and y on the same line separated by a space.

Starter code

main.cpp
#include <iostream>

// Define the swap function

int main() {
    // Declare x and y
    // Add a swap call
    // Print x and y
    return 0;
}

Sample solution

main.cpp
#include <iostream>

void swap(int& a, int& b) {
    int t = a;
    a = b;
    b = t;
}

int main() {
    int x = 1, y = 2;
    swap(x, y);
    std::cout << x << " " << y << "\n";
    return 0;
}

Expected output

2 1

Practice The printSum function

Define a void printSum(const std::vector<int>& v) function; in the body start with int sum = 0;, use a range-based for to add each element to sum, and print sum. In main add 3 and 6 to a std::vector<int>, then call printSum.

Starter code

main.cpp
#include <iostream>
#include <vector>

// Define the printSum function

int main() {
    // Declare the vector and add numbers
    // Add a printSum call
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <vector>

void printSum(const std::vector<int>& v) {
    int sum = 0;
    for (int n : v) {
        sum += n;
    }
    std::cout << sum << "\n";
}

int main() {
    std::vector<int> nums;
    nums.push_back(3);
    nums.push_back(6);
    printSum(nums);
    return 0;
}

Expected output

9

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does this code print?

main.cpp
void swap(int& a, int& b) {
    int t = a;
    a = b;
    b = t;
}
int main() {
    int x = 1, y = 2;
    swap(x, y);
    std::cout << x << " " << y;
    return 0;
}
  • 2 1 Correct answer
  • 1 2
  • 1 1
  • Error

Explanation: swap(x, y) passes by reference, so x and y are exchanged.

2 swap body

Question
void swap(int& a, int& b) { int t = ____; a = b; b = t; }
Answer
void swap(int& a, int& b) { int t = a; a = b; b = t; }

Explanation: int t = a; saves a into a temporary variable.

3 Match the reference tools

Term Meaning
int& r = x Alias
int& n Reference parameter
const int& n Read-only
void swap(int&, int&) Two references

All lessons in Beginner