Learn C++
#include "functions/functions_basics.hpp"

Defining and Calling Functions in C++

//concept

A function packages reusable logic under a name: a return type, a name, a parameter list, and a body. C++ requires declaration before use — define helpers above main() or declare prototypes (signatures ending in ;) up top and define bodies later. Calling runs the body with the arguments bound to parameters, then resumes after the call.

main() itself is just a function with a special role as entry point, returning int as the exit code. Splitting programs into small functions with single responsibilities is the primary tool for taming complexity at every scale.

//how it works
1

Signature anatomy

int add(int a, int b) promises: takes two ints, returns an int. The body between braces fulfills the promise.

2

Declare before use

The compiler reads top to bottom — a function must be declared (prototype) or fully defined before any call to it.

3

Call and resume

add(2, 3) jumps into the body with a=2, b=3; return hands 5 back and execution continues after the call expression.

4

void returns nothing

void greet() performs an action with no result to hand back — callers use it as a bare statement.

//example
#include <iostream>
 
int add(int a, int b) {
return a + b;
}
 
int main() {
std::cout << add(2, 3) << std::endl;
return 0;
}
Output
5
1add is defined above main, so its signature is known when the call is compiled.
2add(2, 3) binds a=2, b=3, computes 5, and returns it to the call site.
3The returned 5 flows straight into cout and prints.
//use cases
Decomposing main() into named helpers as soon as it exceeds a screen
Reusing validation, math, and formatting logic from multiple call sites
Declaring prototypes in headers so other files can call your functions
Unit-testing small pure functions in isolation

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.