Ready to practice?
Sign up to access interactive coding exercises and track your progress.
Function Basics
Learn the basics of creating and calling functions in C++.
Prerequisites
What is a function?
A function is a collection of statements that performs a specific task. Functions are one of the most important features of C++ programming because they allow you to break your code into smaller, manageable pieces.
Think of functions like recipes in a cookbook. Each recipe (function) has:
- A name (like "Scrambled Eggs", i.e.
makeScrambledEggs) - Ingredients (inputs, called parameters, the raw eggs)
- Instructions (the code inside the function)
- A result (the function output, called the return value, eggs anyone?)
Why use functions?
Functions provide several important benefits:
- Organization: Break large problems into smaller, manageable pieces
- Reusability: Write code once and use it many times
- Readability: Make code easier to understand and maintain
- Testing: Test individual pieces of functionality separately
- Collaboration: Different people can work on different functions
Anatomy of a function
Here's the basic structure of a C++ function:
return_type function_name(parameter_list)
{
// function body
// statements to execute
return value; // if return_type is not void
}
Let's break this down:
- return_type: The type of value the function returns (e.g.,
int,double,void) - function_name: The name you give to identify the function
- parameter_list: Input values the function can receive (can be empty)
- function body: The code that runs when the function is called
- return statement: Sends a value back to the caller (optional for void functions)
Your first function
Ok technically your second, main() is also a function.
Here's a simple function that displays messages:
#include <iostream>
void displayMessage()
{
std::cout << "Inside the function" << std::endl;
}
int main()
{
std::cout << "In main, before calling function" << std::endl;
displayMessage();
std::cout << "Back in main, after calling function" << std::endl;
return 0;
}
Output to screen:
In main, before calling function
Inside the function
Back in main, after calling function
Let's analyze this function:
-
Function declaration:
double calculateRectangleArea(double length, double width)- Returns a
doublevalue - Named
calculateRectangleArea - Takes two
doubleparameters:lengthandwidth
- Returns a
-
Function body: Calculates
area = length * width -
Return statement: Returns the calculated area
-
Function call:
calculateRectangleArea(length, width)in the main function
Function calls
To use a function, you call it by writing its name followed by parentheses:
function_name(arguments);
When you call a function:
- Program execution jumps to the function
- The function's code executes
- If there's a return value, it's sent back
- Program execution continues from where the function was called
Example: Multiple function calls
#include <iostream>
void printSeparator()
{
std::cout << "-------------------" << std::endl;
}
int main()
{
std::cout << "Welcome to my program" << std::endl;
printSeparator();
std::cout << "Fake processing data..." << std::endl;
printSeparator();
std::cout << "Done!" << std::endl;
return 0;
}
Output:
Welcome to my program
-------------------
Fake processing data...
-------------------
Done!
Important features of functions
- Functions must be defined before they are used (we'll learn about forward declarations in a later lesson)
- Every C++ program must have a main() function - this is where program execution begins
- Functions can call other functions, including themselves (recursion)
- Variables created inside functions are local to that function
Best practices
- Use descriptive names:
calculateArea()is better thancalc()ora() - Keep functions focused: Each function should do one specific task
- Use consistent naming: Choose a naming style and stick to it
- Add comments: Explain what complex functions do
Summary
Functions transform programming from writing long, repetitive code to building reusable pieces that work together. Just like recipes in cooking, functions take inputs, follow a set of instructions, and produce results. They make your programs:
- More organized - Break complex problems into manageable pieces
- Easier to read - Each function has a clear, single purpose
- Reusable - Write once, use many times
- Easier to debug - Test and fix individual functions separately
Master functions, and you'll write cleaner, more professional C++ code. In the next lesson, you'll learn how functions can return values back to the code that calls them.
Function Basics - Quiz
Test your understanding of the lesson.
Practice Exercises
Creating Basic Functions
Practice writing a simple function that takes no parameters and returns nothing (void).
Lesson Discussion
Share your thoughts and questions