Functions Explained: Turning Repeated Blocks into Reusable Code
Learn how to package repetitive logic into named functions with parameters and return values, keep variable scope clean, and build modular programs in blocks, Python, and C++.
In This Article
- Apply the DRY (Don't Repeat Yourself) principle by replacing copy-pasted code with functions.
- Pass inputs into functions using parameters so a single function can handle different sizes or targets.
- Distinguish between printing a message to the screen and returning a computed value to the caller.
- Understand local variable scope and why variables inside a function don't collide with outside code.
Why Copy-Pasting Code Creates Maintenance Nightmares
As your programs grow beyond twenty or thirty blocks, you will start noticing chunks of logic that appear in multiple places—not necessarily right next to each other where a simple loop could combine them, but scattered across different stages of your program. For example, in a puzzle game, your character might need to unlock and open a heavy door at the beginning of a stage, halfway through a corridor, and again right before the exit. Unlocking a door requires a specific four-step sequence: check inventory for a key, play an unlock animation, decrement the key count, and mark the door tile as passable.
If you copy and paste those four blocks into ten different places in your program and later decide that unlocking a door should also award 50 experience points, you have to hunt down and edit all ten copies. Miss even one copy, and your game has an inconsistent bug. Software engineers summarize the solution with a famous principle: DRY (Don't Repeat Yourself). Instead of duplicating instructions, you define a function (often called a "custom block" or "procedure" in visual programming)—giving a name to a sequence of steps so you can invoke it anywhere with a single call.
Anatomy of a Function: Definition vs. Call
Working with functions always involves two parts:
- Defining the function: Teaching the computer what the new command means by writing its header (its name and expected inputs) and its body (the indented blocks or statements inside curly braces that run when triggered). Defining a function does not execute the code inside it; it merely registers the recipe in memory.
- Calling (or invoking) the function: Actually triggering the recipe by writing the function's name followed by parentheses
(). Each time the program encounters a function call, execution jumps into the function body, runs its statements from top to bottom, and then returns to the exact line where it was called.
Even when a function takes no inputs, notice a crucial rule in almost every programming language: you must define a function before you call it. In C++, the compiler reads your file from top to bottom and must see either the full function definition or a forward declaration before `main()` attempts to call it.
Parameters and Arguments: Making Functions Flexible
A function that always performs the exact same fixed task—like drawing a square of size 3—is helpful, but a function that can draw a square of any size is far more powerful. To make functions customizable, we give them parameters.
Parameters are special input variables listed inside the parentheses of a function's definition. When you call the function, you pass concrete values (called arguments) into those parentheses. The function automatically assigns your arguments to its parameter variables before running its body.
Visual Block Logic
DEFINE walk_square(side_length):
REPEAT 4 TIMES:
REPEAT side_length TIMES:
move_forward()
turn_right()
// Calling the custom block:
walk_square(3)
walk_square(6)
Python
def walk_square(robot, side_length):
for _ in range(4):
for _ in range(side_length):
robot.move_forward()
robot.turn_right()
# Calling the function:
walk_square(bot, 3)
walk_square(bot, 6)
C++
void walkSquare(Robot& robot, int sideLength) {
for (int i = 0; i < 4; ++i) {
for (int s = 0; s < sideLength; ++s) {
robot.moveForward();
}
robot.turnRight();
}
}
// Calling inside main():
walkSquare(bot, 3);
walkSquare(bot, 6);
Return Values: Sending Answers Back to the Caller
Some functions exist purely to perform an action (like moving a robot or printing a message on screen). In C++, functions that do not send back a value have a return type of void. However, many functions exist to compute an answer and hand that answer back to the code that called them—such as calculating the Manhattan distance between two grid tiles or computing final damage after armor reduction.
To send a result back, use the return keyword. When a return statement executes, two things happen immediately:
- The expression following
returnis handed back to the caller, replacing the function call expression itself. - The function terminates immediately. Any lines of code written after an executed
returnstatement inside the same block are skipped completely.
Visual Block Logic
DEFINE manhattan_dist(x1, y1, x2, y2):
SET dx TO abs(x2 - x1)
SET dy TO abs(y2 - y1)
RETURN dx + dy
SET steps_needed TO manhattan_dist(1, 2, 5, 7)
Python
def manhattan_dist(x1, y1, x2, y2):
dx = abs(x2 - x1)
dy = abs(y2 - y1)
return dx + dy
steps_needed = manhattan_dist(1, 2, 5, 7)
C++
int manhattanDist(int x1, int y1, int x2, int y2) {
int dx = std::abs(x2 - x1);
int dy = std::abs(y2 - y1);
return dx + dy;
}
int stepsNeeded = manhattanDist(1, 2, 5, 7);
print with return. Printing displays text for a human reading the console, but the computer cannot use printed text in further math. Returning hands the actual data value back to the calling code so you can store it in a variable or combine it in larger expressions.Local Scope vs. Global State
Notice the variables dx and dy created inside manhattan_dist above. Where do those variables live? They have local scope. They are created fresh each time the function is called, exist only while the function is running, and are automatically erased from memory the moment the function returns. If you try to read dx outside of manhattan_dist, Python and C++ will report an "undefined variable" error.
Local scope is a massive advantage: it means two different functions can both use a local variable named dx or count without accidentally overwriting each other's data. Each function acts as a self-contained black box—inputs enter through parameters, temporary work stays private inside local variables, and the final result exits cleanly through return.
Pass-by-Value vs. Pass-by-Reference in C++
When you pass an integer variable like int size = 5; into a C++ function void shrink(int s), C++ copies the value 5 into a brand-new local variable s. Modifying s inside the function never affects the original size variable in main()—this default behavior is called pass-by-value. By contrast, if a function needs to modify an object directly (like moving our Robot& robot parameter in walkSquare above), adding an ampersand & creates a reference to the original object rather than duplicating it. Keeping most functions pure—taking values in and returning a new value out without hidden side effects on global variables—makes debugging ten times easier.
Practice Exercise: Refactoring Duplicate Logic
Consider a game where a player earns stars after completing a puzzle based on how many moves they took compared to the level's par target:
- If
moves <= par, the player earns3stars. - If
moves <= par + 3, the player earns2stars. - Otherwise, the player earns
1star.
Write a function named calculate_stars(moves, par) in both Python and C++ that accepts those two integers and returns the integer star rating (1, 2, or 3). Then show how to call your function for three different levels and sum their returned values into a single variable named total_stars.
CodeCracker