×

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

Unary Operators in C++

Unary operators in C++ Unary operator: is operations that function to produce a new value on a single operand. a) unary minus: A minus operator modifies the argument's symbol. A positive number...

3 minutes read.

wcscpy(), wcslen(), wcscmp() Functions in C++

There are many built-in functions in C++ programming language which differentiate it from C programming language in most hardware-coded languages. We will now closely look into the applications of three...

4 minutes read.

10 Best C and C++ Books for Beginners & Advanced Programmers

If you want to become a skilled software developer, you should never stop learning, whether you're a working professional or a student. Why, therefore, only C or C++? The fundamental...

6 minutes read.

Diamond Pattern Using Do-While loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

5 minutes read.

C++ storage classes

Storage Classes are used to characterize a variable's or function's characteristics. These characteristics include scope, visibility, and life-time, which allow us to track the presence of a variable over the...

5 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.

Delete Operator in C++

Overview We can reserve allocation for a variable or an array at runtime in C++. Dynamic memory allocation is the term for this. After utilising a variable in C++, we must...

4 minutes read.

What does Buffer Flush mean in C++

A buffer flush, to explain simple layman's terms, is nothing but the transfer of computer data which is being stored in a rentable temporary memory of your computer running either...

3 minutes read.

4 Pillars of OOPs

OOPs OOPS means Object Oriented Programming System Structure. Object oriented Programming is defined as an approach that provides a way of modularizing programs by creating partitioned memory area for both data...

11 minutes read.

Types of polymorphism in C++

What is polymorphism in C++ ? Polymorphism literally translates to "multiple forms". This indicates that the same thing behaves differently depending on the context in programming. Polymorphism is a feature of C++...

6 minutes read.

C++ Virtual Function

A virtual function is such function which is declared inside the base class and redefined by the derive class. C++ uses a virtual keyword to make a function as a virtual function. The virtual...

1 minute read.

Difference between Exit and Return

Define Exit() At the point when a client needs to leave a program from this capability is utilized. A void return type capability calls all capabilities enrolled at the exit and ends...

3 minutes read.

Structure Vs Class in C++

The structure in C++ is similar to that of a class, with a few exceptions. Both the structure and the stage, the most important thing is safety. The property is...

4 minutes read.

C++ array of Pointers

Array of Pointers: In high-level programming languages like C++, the array's name is its pointer. The name of an array contains an address which is the address of an element. In...

4 minutes read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

Print Table Using For-loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

3 minutes read.

Similarities between C++ and Java

People who are preparing for software engineering roles must have come across either one of these languages because as all the companies do not accept python for hiring a fresher...

3 minutes read.

C++ OOPs Concept

The main goal of C ++ programming is to add the idea of ​​object orientation to the C programming language. Inheritance, data binding, polymorphism and other concepts are part of...

4 minutes read.

C ++ Program: Alphabet Triangle and Number Triangle

Alphabet Triangle and Number Triangle An alphabet triangle is a triangle that typically looks like a pyramid or other triangles like an isosceles triangle, a right-angled triangle consisting of similar or...

4 minutes read.

Nullptr in C++

What is Nullptr in C++? A null pointer value is represented by the term nullptr. Use a null pointer value to indicate that a native pointer type, inner pointer, or object...

3 minutes read.