Functions in C++
Explore how functions in C++ allow you to write reusable, modular code by defining named blocks of instructions. Understand the difference between built-in library functions and user-defined functions, and learn why using functions simplifies programming and debugging.
We'll cover the following...
Introduction
Suppose you want to make juice for yourself. You will follow the following steps:
- Put fruits and water in a blender.
- Turn on the juicer.
- Enjoy the juice after 1 minute.
A function is like a blender that performs a specific action on some ingredients and returns a modified product. We can use the same blender to extract the juice of different fruits. Similarly, functions are reusable, and we can use the same function anytime with different inputs.
In computer language, a function is a block of code that performs a particular task. It is also given a name.
Functions in programming are just like mathematical functions. They take something as input, perform some operation on it, and return an output.
Types of functions
In C++, we have two types of functions:
- Library functions
- User-defined functions
Library functions
These functions are also known as built-in functions. They are already defined in the C++ header files such as \<iostream>, \<string>, and \<cmath> etc. We can use these functions by including the relevant header file and then call them later in a program.
User-defined functions
These functions are defined by users according to their needs. We can call them anywhere in the current program.
Why use functions?
We use functions in a program to:
- Make our code reusable
- Divide our code into small modules
- Make the debugging of the program easier
- Make our code neat
- Avoid code repetition
📝 The purpose of a function is to define the code block once and then use it many times.