×

C++ Functions

In other programming languages, a function is referred to as a process or a subroutine. We can design functions to execute any task. A function can be used repeatedly. It allows for code reuse and modularity.

Benefits of Function in C++

There are many benefits of function in C++:

Reusability of Code: You can invoke functions created in C++ multiple times. As a result, we won't have to write the same code again and over.

Optimization of code: It optimizes the code so that we don't have to write as much. Assume you need to determine if three numbers (521, 833, and 715) are prime. You must write the prime number logic three times without using a function. As a result, there is code repetition.

Function Types in C++

In C++ programming, there are two types of functions:

Function in C++

Library Functions: These are functions like ceil (i), cos (i), exp (i), and others that are declared in C++ header files. When you utilize functions, though, you only have to write the logic once and it may be reused several times.

User-defined functions: These are functions that a C++ programmer creates so that he or she may reuse them. It optimizes the code and minimizes the complexity of a large program.

How to Declare a Function in C++?

The following is the C++ syntax for creating a function:

return_type function_name(data_type parameter...)  
{    
//code to be executed    
}  

Example of a program in C++ showing the work of function:

#include <iostream>  
#include <bits/stdc++.h>
#include <stdlib>
using namespace std;  
void function() {    
   static int a=0; //static variable    
   int b=0; //local variable    
   a++;    
   b++;    
   cout<<"a=" << a<<" and b=" <<b<<endl;    
}    
int main()  
{  
 function();    
 function();    
 function();    
}  

OUTPUT:

a= 1 and b= 2
a=2 and b=1
a=3 and b=1
.................
Process executed in 435.3 seconds
Press any key to exit.

Explanation

In the above program in C++, we made a void function which takes a static variable and a local variable and we make a call to the void function from main function to print the values of a and b respectively.

What is the purpose of functions in C++?

  • We may reduce code repetition by using functions. If a function is used several times in software, rather of duplicating the same code again and over, we construct a function and use it everywhere. This also helps with maintenance because we just have to make changes to the functionality once.
  • Code is modularized thanks to functions. Consider a large file with several lines of code. When code is separated into functions, it becomes much easier to understand and utilize.
  • Abstraction comes from functions. For example, we can utilize library functions without having to worry about how they operate inside.

Parameter in Functions

Actual parameters are the arguments supplied to the function. 10 and 20 are, for example, actual parameters in the given application. Formal parameters are the parameters that a function receives. In the given program, formal parameters x and y are used. There are two common methods for passing arguments.

Pass by Value: Actual parameter values are copied to the official function parameters in this parameter pass process, and two types of parameters are stored in separate memory locations. As a result, any modifications done within functions do not appear in the caller's real arguments.

Reference Passage: Because both the actual and formal arguments relate to the same places, any changes performed inside the function are mirrored in the caller's actual parameters.

In C, parameter values are always supplied by value. For example, the function does not change the value of i in the code below ().

#include <stdio.h>
#include <iostream>
#include <bits/stdc++.h>
#include <stdlib>
void fun(int i)
{
i = 40;
}
int main(void)
{
	int i = 10;
	fun(i);
	printf("i = %d", i);
	return 0;
}

OUTPUT:

i = 10

Explanation

In the above code in C++, the function does not change the value of i because the function call was made above before printing the value.

Another example:

#include <iostream>
#inlcude <bits/stdc++.h>
#include <stdlib>
using namespace std; 
void fun(int *pter)
{
	*pter = 40;
}
int main() {
	int i = 20;
	function(&i);
	cout << "i = " << i; 
	return 0;
}

OUTPUT:

i= 40

Explanation

In C, though, we may achieve the same effect by using pointers. Consider the sample program below. The method function () requires an integer pointer pter (or an address of an integer). It changes the value at the pter address. The value at an address is accessed via the dereference operator *. The value at address pter is changed to 40 in the sentence '*pter = 40'. The address operator & is used to find the address of any data type variable. The address of i is supplied in the function call statement 'function(&i)' so that i can be updated using its address.

IMPORTANT:

  • When a user starts a program written in C, the operating system calls a method called main().
  • There is a kind of restoration in every work. If the function returns nothing, the return type does not work. Furthermore, if the function's return type is void, we may still use the return statement in the body of the function declaration without providing any constants, variables, or other parameters.
  • Except for arrays and functions, functions in C can return any type. We can get around this restriction by returning a reference to an array or a function pointer.
  • In C, an empty parameter list indicates that no arguments are given and that the function can be called with any parameters. In C, declaring a function like fun is not a smart idea (). "void fun(void)" should be used to declare a function that can only be invoked without any parameters.

Related Topics

Initialize Array of objects with parameterized constructors in C++

Initialize Array of objects with parameterized constructors in C++ When a class is defined, only the specification for the object is specified; no memory or capacity is allocated. You need to...

3 minutes read.

C++ | C Plus Plus Data type

Data type in every language is very important. Data type means the different kinds of data that are supported by a particular programming language. A computer language’s data types specify the...

15 minutes read.

Method overriding in C++

What is method overriding? Using the same function in derived class as their base class is referred to as function/method overriding in c++. Method overriding is an example of polymorphism. With...

2 minutes read.

Learn C++ Tutorial

C++ Introduction C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories. It is superset (extension) of C programming language. Depending upon features supported by programming...

10 minutes read.

C++ If

C++ Control Statement C++ control statement or decision-making statement is used to control the flow of program statement according to condition applied. C++ if Control Statement An if control statement in C++ is used to...

2 minutes read.

Implementation of a Falling Matrix in C++

In many Hollywood and Bollywood movies, we might have seen a programmer who will be referred to as a hacker all the time for some random reason which the writer...

3 minutes read.

This keyword in C++

This keyword in C++ is a pointer which points to the object. It is passed as an argument to functions which helps in accessing the object. It is used for a...

3 minutes read.

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed. Constructor Characteristics Constructors...

3 minutes read.

C++ Functions

In other programming languages, a function is referred to as a process or a subroutine. We can design functions to execute any task. A function can be used repeatedly. It...

5 minutes read.

Passing a Vector to a function in C++

A pointer is sent to the function when we feed it an array. However, there are two ways to pass a vector: Pass by Value Pass by Reference A copy of a vector...

3 minutes read.

C++ Program to find the product array puzzle

Write a C++ program to form a product array from arr[] where product[i] is the product of all the array elements except arr[i]. Example Input: arr[]  = {10, 3, 5, 6,...

6 minutes read.

C++ Exception Handling

Exception is an unexpected problem that occurs at program run time. This problem might include condition such as division by zero, running out of memory space, array out of bonds, etc....

2 minutes read.

Quick Sort in C++

Quick sort is an efficient, in-place, comparison-based sorting algorithm that uses a divide-and-conquer strategy to sort an array or list of elements. First a pivot element is selected from the...

4 minutes read.

C++ this pointer

'this' is a pointer that points to the object for which this function was called. The 'this' pointer holds the memory address of the current object. The 'this' pointer is implicitly passed to...

2 minutes read.

C++ Call by Value

In this article, we will discuss C++ Call by Value with their syntax, examples, use cases, advantages, and disadvantages. C++ Function A function is a set of statements that executes a task....

5 minutes read.

Design Patterns in C++

A design pattern offers an all-encompassing, repeatable answer to the typical issues that arise in software design. Usually, the pattern demonstrates the connections and interactions between several classes or objects....

10 minutes read.

C++ Multimap

Definition: In C++, a multimap is similar to a map with the additional concept, where multiple elements possess the same keys. It is also not necessary that the key values and...

4 minutes read.

Single Handling in C++

Introduction: Single handling in C++ refers to a technique for processing multiple events or requests with a single function or handler rather than creating separate functions for each task. This allows...

5 minutes read.

C++ Switch

In C++, an expression or variable can be tested against a range of constant values using a switch statement, which is a control flow statement. It offers a productive method...

4 minutes read.

Diamond Pattern using While-loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

5 minutes read.