Um momento
0x30Lesson 4 of 9

Build functions and pass by reference

Give work a name, return results, and avoid unnecessary copies.

16 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Declare functions and distinguish value, reference, and const-reference parameters.

Functions package reusable behavior behind a name and parameter list. A function can return a value or use void when it returns nothing. Passing an argument by value makes a copy; passing by reference with & lets a function refer to the caller’s object. Add const to a reference when a function should read without modifying. A const reference is efficient for large inputs, while a small integer is usually clear and cheap by value.

main.cpp · C++20
1#include <iostream>
2#include <string>
3
4void greet(const std::string& name) {
5    std::cout << "Hello, " << name << "!\n";
6}
7
8int main() {
9    greet("Ada");
10}
Output
Hello, Ada!

The declaration must be visible before a call, either through a prior function declaration or a definition placed earlier. In modern C++, prefer references and standard-library types over manual pointer parameters when nullable or reseatable behavior is not needed.

Key takeaways

  • Functions make behavior reusable and nameable.

  • Use references to avoid copies or intentionally modify caller state.

  • Use const references for large read-only inputs.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write C++

Write C++20 in the editor and run it against sample input. GCC 14 compiles the code through Compiler Explorer, a free public service; your source and test input are sent there.

Exercise 1

Write a reusable square function

+25 XP

Implement square so it returns the input multiplied by itself. Read one integer and print the result.

  • Square 4
  • Square -3
main.c
Loading editor…

Your code is compiled as C++20 with gcc 14 (-Wall -Wextra) and run on Compiler Explorer (godbolt.org), a free public service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: