Functions in C++ are code blocks that are used to perform a particular task and make code reusable, readable, efficient, and maintainable. They are the backbone of C++ programming. Thus, whether you are a beginner or an experienced programmer, you must know how to use functions effectively and efficiently. In this article, we will discuss what a function is in C++, types of functions, parameters and arguments, function calling, recursion, function overloading, and other special types of functions in C++.
Table of Contents:
What is a Function in C++?
A function in C++ is a block of code that performs a particular task. Functions help to write a part of the code once and reuse it wherever needed. This feature of functions makes the program modular, easier to read, maintain, and debug. Thus, instead of writing the same logic multiple times, the logic can be encapsulated inside the function, and it can be called whenever it is needed.
Basic Syntax of a Function:
return_type function_name(parameter_list) {
// function body
}
Parameters:
- return_type: It is the data type of the value the function will return.
- function_name: It is the name of the function by which it can be identified.
- parameter_list: It is a list of input parameters, and it can be empty.
- Function body: It is the set of statements that define what the function does.
Example:
Output:
The code shows how the function greet() is defined, and then called from the main() function to print “Hello from a function!” to the console.
Types of Functions in C++
There are two types of functions in C++:
- Built-in Functions
- User-defined Functions
Built-in Functions in C++
Built-in functions in C++ are predefined functions provided by the C++ standard libraries. They help to perform common tasks such as mathematical operations, input/output handling, and string manipulation. They are also known as Library functions.
Category |
Functions |
Header File |
Purpose |
Mathematical |
sqrt(), pow(), abs() |
<cmath> |
Perform common math operations |
Character Handling |
isalpha(), isdigit() |
<cctype> |
Check character types (letter, digit, etc.) |
String Operations |
strlen(), strcpy(), strcmp() |
<cstring> |
Work with C-style strings |
Input/Output |
cin, cout, getline() |
<iostream> |
Handle input and output streams |
Utility Functions |
exit(), malloc() |
<cstdlib> |
General-purpose utilities |
Time Functions |
time(), clock() |
<ctime> |
Deal with time and date |
Example:
Output:
The code shows how the built-in sqrt function is used from the <cmath> library to calculate and print the square root of 25 to the console.
User-defined Functions in C++
User-defined functions in C++ are the functions that are created by programmers to perform particular tasks. They also help make code reusable, organized, and easier to manage. A user-defined function typically involves declaring, defining, and calling the function.
Example:
Output:
The code shows how a user-defined function add() is defined to get the sum of two integers a and b, and called in the main() function, and then the sum, 8, is printed to the console.
Parameters and Arguments in Functions in C++
- Parameters are variables listed in the parentheses in a function definition.
- Arguments are the actual values that are passed to the function when the function is called.
Example:
Output:
The code shows that string name and int age are the parameters that are defined in the greet() function, and “Nirnayika”, 21, and “Pooja”, 25, are the arguments that are passed when the greet() function is called.
Default Arguments in Functions in C++
Default arguments in C++ allow assigning default values to function parameters. If no argument is passed for the parameter during the function call, then the default value is automatically used.
Example:
Output:
The code shows how a function greet() is defined with a default argument “Guest” and called twice, first with “Yash” and second without any argument using the default value, and then the result is printed to the console.
Function Calling in C++
Function calling in C++ is the process of executing a function by using its name. When a function is called, control jumps to the function body, executes the function body code, and then returns to the point where the function was called.
There are three methods to call a function in C++:
Methods |
Description |
Example |
Call by Value |
A copy of the actual value is passed, and the changes inside the function do not affect the original value. |
display(x) |
Call by Reference |
The actual variable is passed and changes inside the function affect the original value. |
display(&x) (using reference or pointer) |
Call by Pointer |
The address of the variable is passed and used to modify the original value through pointers. |
display(&x) |
Example:
Output:
The code shows how the original num 5 does not change and remains the same as 5 by using the call by value method to call the function, but it changes by using the call by reference method, it changes to 25, and by using the call by pointer method, it changes to 55.
Recursion in C++
Recursion is a programming technique in which a function calls itself. A function that calls itself is known as a recursive function. In recursion, there are two main cases: the base case, which is a condition that stops the recursion to prevent infinite calls, and the recursive case, in which the function calls itself with a changed or modified argument. Recursion is used for problems such as tree traversal, the Fibonacci series, factorials, etc.
Example:
Output:
The code shows how a recursive function, factorial(), is used to calculate the factorial of a number, 5, where the function calls itself until it reaches the base case (factorial(0)), which returns 1, and then the main function returns the factorial of 5 as a result.
Function Overloading in C++
Function overloading is the process of defining multiple functions with the same name but different parameter lists. The compiler decides which function is to be called based on the arguments passed.
There are two ways by which a function can be overloaded in C++:
Type |
Description |
Based on the Number of Parameters |
Functions have the same name but different numbers of parameters. |
Based on the Type of Parameters |
Functions have the same name and number of parameters but different types. |
Example:
Output:
The code shows how the function is overloaded by changing the number and type of parameters with the same function name, add(), to perform different operations based on the passed arguments, and then prints the result to the console.
Function Local Variables in C++
Local variables in C++ are the variables that are declared inside a function. These variables can be created when the function is called and can be destroyed when the function ends, which means that local variables exist only within the scope of a function. There are a few methods that can help to access a local variable’s memory outside of its scope, but these methods can cause errors or undefined behavior if not used properly.
Example:
Output:
The code shows how a local variable localVar inside the show() function is defined, which can be accessed only within this function and cannot be used outside the function. Thus, if the main function tries to access, then it will lead to an error.
Function Pointers in C++
A function pointer is a pointer in C++ that points to a function instead of a value. It helps in
calling functions dynamically at runtime, passing functions as arguments to other functions, and creating arrays of functions.
Syntax:
return_type (*pointer_name)(parameter_list);
Example:
Output:
The code shows how a function pointer, funcPtr, is used to store the address of the greet() function and call the function indirectly, thus printing the message “Hello from Intellipaat!” as an output on calling.
Difference Between Function and Function Pointer in C++
Aspect |
Function |
Function Pointer |
Definition |
A code block with a name that performs a task. |
A variable that holds the address of a function. |
Calling Mechanism |
Directly by name. |
Indirectly through the pointer. |
Declaration Syntax |
void greet(); |
void (*ptr)(); |
Assignment |
Not needed, it is defined only once. |
Needs explicit assignment, such as ptr = greet; . |
Memory |
Code is stored in the code section, with no extra memory for access. |
Pointer stores the address of a function. |
Flexibility |
Statically bound at compile-time. |
Can be changed at runtime to point to different functions. |
Purpose |
Perform fixed tasks. |
Allow dynamic function selection and callbacks. |
Examples |
Regular programs, simple calculations. |
Event-driven programs, callbacks, plugins, and function tables. |
Type Safety |
Fully type-checked by the compiler. |
Must match the exact function signature because a type mismatch causes errors. |
Complexity |
Simple. |
Slightly complex. |
Inline Functions in C++
An inline function is a special function in C++ in which the compiler tries to insert the code of a function directly into the place where the function is called instead of calling the function. It helps in increasing the execution speed by avoiding the overhead of a function call. It is best for small and simple functions.
Syntax:
inline return_type function_name(parameters) {
// function body
}
Example:
Output:
The code shows how an inline function square() is used to directly insert the multiplication code where the square function is called, and then the square of 5 is 25 and is printed as output to the console.
Difference between Function and Inline Function in C++
Aspect |
Function |
Inline Function |
Definition |
A function is declared with the return_type function_name(). |
A function prefixed with the inline keyword. |
Function Call Mechanism |
A call to the function involves overhead. |
The function’s code is inserted directly into the place where the function is called and avoids function call overhead. |
Execution Speed |
Slower due to the function call overhead. |
Faster for small functions because of reduced overhead. |
Memory |
Uses memory for the function’s call stack. |
May increase code size due to multiple insertions in the code. |
Best Use Case |
It is used for complex operations or functions called less frequently. |
Best for small, frequently used functions. |
Recursive Functions |
Can be recursive. |
Cannot be recursive (compiler can’t inline a recursive function). |
Compiler’s Role |
The function code exists separately, and the compiler manages calls. |
The compiler attempts to replace the function call with the actual function code. |
Code Bloat |
No code bloat. |
It can cause code bloat if the function is called many times. |
Lambda Functions in C++
A lambda function in C++ is an anonymous function that can be defined inline at the point where it is used. It is particularly used for short-lived operations. It also eliminates the need for function pointers and makes code more readable and maintainable.
Syntax:
[ capture_clause ] ( parameter_list ) -> return_type { function_body }
- capture_clause: It specifies which variable can be accessed inside the lambda from the surrounding scope.
- parameter_list: It is a list of input parameters.
- return_type: It shows the type of the value returned.
Example:
Output:
The code shows how a lambda function add is defined to add two integers a and b, and then it is called to print the sum of 5 and 3 is 8, to the console as an output.
Difference Between Function and Lambda Function in C++
Aspect |
Function |
Lambda Function |
Definition |
Defined using a regular function declaration. |
Defined inline using the []() syntax. |
Name |
It has a name. |
It is anonymous, does not have a name unless assigned to a variable. |
Syntax |
return_type function_name(parameters) { body } |
[capture](parameters) -> return_type { body } |
Memory |
Stored as a separate function in memory. |
Implemented as a function object (a callable object). |
Functionality |
It can be called multiple times, and can have parameters and return types. |
It can capture variables from the surrounding scope and is typically used for small, short-lived operations. |
Scope |
It only exists within the scope of the function or globally. |
It exists only where it is defined or where assigned to a variable. |
Performance |
May involve function call overhead. |
May reduce overhead, but can increase code size if overused. |
const and constexpr Functions in C++
Both const and constexpr functions in C++ are used to define variables or functions that are evaluated at compile time.
Let’s discuss each of the functions in brief with examples in C++.
const Function
A const function in C++ is a member function of a class that uses the const keyword and does not allow modification of any member variables of the object it belongs to. It is declared using the const after the function signature. It makes code safer and also predictable. If the value inside the const function is tried to be modified, then the compiler will throw an error.
Syntax:
return_type function_name(parameters) const {
// function body (cannot modify object’s data)
}
Example:
Output:
The code shows how a const member function, getValue(), is used to return the value 10 without modifying the object, and then prints the output to the console.
constexpr Function
A constexpr function in C++ is a function that is calculated at compile-time. It is used to create a constant expression that makes the programs faster. It is declared by using the constexpr keyword before the function definition.
Syntax:
constexpr return_type function_name(parameters) {
// must return a constant expression
}
Example:
Output:
The code shows how a constexpr function, area(), is used to calculate the area of a rectangle using length and width at compile-time, and then prints the result, 50, to the console.
Difference between const and constexpr Functions in C++
Aspect |
const Function |
constexpr Function |
Purpose |
It guarantees no modification of the object state. |
It allows compile-time evaluation of a function if possible. |
Usage |
It is used only for class member functions. |
It is used for both normal and member functions. |
When evaluated |
It is always evaluated at runtime, but ensures safety. |
It is evaluated at compile-time if inputs are constant, otherwise at runtime. |
Syntax |
return_type function_name() const {} |
constexpr return_type function_name() {} |
Restrictions |
It cannot modify non-mutable members. |
The function body must be simple and valid in constant expressions. |
Example |
int getValue() const; |
constexpr int square(int x); |
Benefit |
It provides read-only access to object data. |
It provides precomputed values and optimization. |
Conclusion
Functions are blocks of code that can be used in C++ code to perform a specific task. The use of functions will also help to make the code more readable, modular, and maintainable. Additionally, you have different kinds of functions in C++, including user-defined functions, lambda functions, and inline functions. Therefore, by understanding what a function is, how a function works, the function parameters, recursion, overloading, and some special types of functions in C++, you should be able to use functions to write a useful C++ program.
Function in C++ – FAQs
Q1. What is a function in C++?
A function in C++ is a block of code that is used to perform a particular task.
Q2. What are the types of functions in C++?
There are two types of functions in C++, built-in functions, which are provided by the C++ libraries, and user-defined functions, which are created by programmers.
Q3. What is function overloading?
Function overloading is the process that allows us to define multiple functions with the same name but different parameter types and numbers.
Q4. What is the difference between a function and a function pointer?
The difference between a function and a function pointer is that a function is a block of code, and a function pointer stores the address of a function.
Q5. When should I use inline functions?
You should use inline functions for small functions to reduce function call overhead.