Functions in C++

Video Tutorial
FREE
Functions Introduction thumbnail
This video belongs to
C++ Course: Learn the Essentials
14 modules
Certificate
Topics Covered

A function is essentially a set of instructions designed to perform a specific task. It accepts input, carries out computations, and generates output. By grouping commonly used tasks together, functions allow for efficient code reuse, eliminating the need to rewrite the same code for various inputs. In essence, a function is a segment of code that executes only when invoked.

Syntax

Example

Output:

Complexity Analysis: The factorial function's time complexity is O(n), where n represents the input number.. The space complexity is also O(n) due to the recursive calls, which create a stack frame for each function call until reaching the base case.

Points to Remember About Functions in C++

  1. Syntax: Functions in C++ have a specific structure with a return type, name, parameters, and a function body.
  2. Return Type: Specifies the data type of the value returned by the function. It can be void if the function doesn't return any value.
  3. Parameters: Functions can accept parameters, allowing data to be passed into the function for processing.
  4. Function Call: To use a function, it must be called from within the program, specifying the function name and providing any required arguments.

Why do We Need Function?

Functions in C++:

  1. Reduces Code Redundancy: Functions avoid repetition by encapsulating repeated tasks, promoting efficient maintenance.
  2. Enhances Modularity: Segments extensive code into manageable units, improving readability and usability.
  3. Provides Abstraction: Encapsulates complex logic, allowing use of library functions without delving into implementation details.
  4. Streamlines Maintenance: Centralizes modifications, requiring changes in only one place, simplifying maintenance efforts.

Types of Functions in C++

User Defined Functions

Functions created by the user for custom requirements are called user-defined functions. A user-defined function in C++ is designed to accomplish a specific task and can be invoked multiple times from any part of the program. A program can have multiple user-defined functions.

A user-defined function has:

  • Function name
  • Return type
  • Function parameters
  • Function body

User Defined Functions in C++

Function body contains the code statements that perform the required task. The function body is only executed when the function is called.

Library Functions

These functions are already defined in C++ header files and STL ( Standard template library ). Header files are special files with .h extension. We have to include the header file of the function before calling it using the include directive.

For example: pow() function in C++ is defined in math.h header file. It returns the result of the first argument raised to the power of the second argument.

Output

Parameters Passing to Functions in C++

Two common parameter passing methods are:

  1. Pass by Value: This method involves copying the values of actual parameters into the function's formal parameters. As a result, changes made within the function do not affect the original parameters in the caller's context. Each parameter resides in its own memory location.

Function call by value

  1. Pass by Reference: Here, both actual and formal parameters share the same memory locations. Consequently, modifications made inside the function directly impact the original parameters in the caller's context.

Function call by reference

Difference Between Call by Value and Call by Reference in C++

Function Definition in C++

The function definition is the most important part. A function in C++ comprises the return type, function name, parameter list, and the actual implementation logic. The code within the function body is executed only upon calling the function.

In C++ language, the function body is enclosed in curly braces.

Syntax for function Definition:

C++ language allows us to declare and define the function at the same time.

Note that in the function declaration, it is not important to specify the name of parameters but in the function definition, it is mandatory to write names with the data type.

To understand better, let's look at an example. Here is how we can write a function for calculating the sum of the elements of an array.

Function Using Pointers

Imagine a situation where there's a function called increment() that accepts a pointer ptr to an integer as its parameter. This function works by increasing the value stored at the memory location indicated by ptr. By using the dereference operator *, the value at the address ptr is modified within the function. The address operator & retrieves the address of a variable. When calling the function increment() with &num, the address of num is passed, allowing the function to modify num directly using its address.

In this example, the increment() function increments the value of num from 10 to 11 by directly modifying the memory location of num.

Output:

C++ Main Function

The main() function is vital in every C++ program, serving as its entry point. It marks where the program execution begins. There are two types of main() functions:

  1. Without Parameters:
  1. With Parameters (for command line input):

Using parameters in main() facilitates command line input by storing arguments as elements in the argv array. The return type of int mandates including a return statement, where returning 0 signifies successful execution to the calling program.

What is Recursion in C++?

Recursion in C++ occurs when a function calls itself, creating a chain of function calls. The function calling itself is termed a recursive function. If a function calls itself and does not perform any tasks after the function call, it is referred to as tail recursion. In tail recursion, the same function is typically called with a return statement.

Syntax:

Passing Array to Function in C++

In C++, arrays can be passed to functions to reuse array logic. To pass an array to a function, only the array name needs to be provided.

Syntax:

Example: Calculate the sum of elements in the given array.

Function Overloading in C++

Function overloading in C++ allows multiple functions to have the same name but different parameters. This enhances code readability and reusability.

Example 1: Changing the number of arguments.

Example 2: Varying types of arguments.

Function overloading can lead to ambiguity in certain cases, such as type conversion, functions with default arguments, and functions with pass-by-reference parameters. These situations can cause compilation errors when the compiler is unable to determine which function to invoke.

Friend Function in C++

A friend function in C++ allows access to private and protected members of a class, even though it is not a member of that class. It's declared using the keyword "friend" inside the class.

Example 1: Calculate the sum of two private members of different objects using a friend function.

In above example, the function sum is declared as a friend function inside the Numbers class. It can access the private members num1 and num2 of both obj1 and obj2. When called, it returns the sum of all four private members.

Output:

Conclusion

  1. Functions in C++ are essential for organizing code into reusable, modular units, enhancing readability and maintainability.
  2. They can be user-defined or library functions, catering to custom requirements or providing pre-defined functionality.
  3. Parameter passing methods include pass by value and pass by reference, offering flexibility in data manipulation.
  4. Recursive functions in c++ allow for elegant solutions to problems by calling themselves, while function overloading enhances code flexibility.
  5. Friend functions in c++ enable access to private and protected members of a class, even from outside the class scope.
  6. Mastering functions in C++ is fundamental for writing efficient, structured, and scalable code.