Ch6.1: What is a Function?
Overview
A function is a reusable block of code that performs a specific task.
You have already used many functions in earlier chapters:
main, ::fast_io::println,
::fast_io::scan, and constructors of containers.
Functions allow you to:
- organize code into meaningful units
- avoid repeating the same logic
- give names to operations
- separate what a program does from how it does it
In this chapter, you will learn the basic structure of a function, how to call functions, and how return values work.
1. Basic function syntax
A function has four parts:
- a return type
- a name
- a parameter list
- a body enclosed in braces
int add(int a, int b)
{
return a + b;
}
This function takes two integers and returns their sum.
Calling a function
#include <fast_io.h>
int add(int a, int b)
{
return a + b;
}
int main()
{
using namespace ::fast_io::iomnp;
int result = add(10, 20);
println("Result = ", result);
}
The expression add(10, 20) calls the function and produces a value.
2. The void return type
A function that does not return a value uses the void type.
void greet()
{
using namespace ::fast_io::iomnp;
print("Hello!\n");
}
A void function is called the same way:
greet();
Because it returns nothing, you cannot write:
// int x = greet(); // ❌ error — greet() returns void
3. Parameters and arguments
The variables inside the parentheses of a function definition are called parameters. When you call the function, the values you pass in are called arguments.
int square(int x)
{
return x * x;
}
int y = square(5); // 5 is the argument
Parameters behave like local variables inside the function.
4. Return statements
A function returns a value using the return statement.
double half(double x)
{
return x / 2.0;
}
A return statement immediately ends the function.
int test(int x)
{
if(x < 0)
return -1; // function ends here
return x * 2; // otherwise return this
}
5. Why functions matter
Functions are the foundation of all higher‑level abstractions in C++. They make programs:
- easier to read
- easier to test
- easier to maintain
- less repetitive
Later chapters will show how functions interact with references, objects, templates, and lambdas. For now, the goal is simply to understand how to define and call them.
Key takeaways
- A function groups code into a reusable unit.
- A function has a return type, name, parameters, and a body.
voidmeans “returns nothing”.- Parameters are local variables inside the function.
- Arguments are the values passed when calling the function.
returnends the function and produces a value.