Skip to main content

Function in C++, Call by Value , Call in Reference

C++ Functions

The function in C++ language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C++, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (531, 883 and 781) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Types of Functions

There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C++ header files such as ceil(x), cos(x), exp(x), etc.

2. User-defined functions: are the functions which are created by the C++ programmer, so that he/she can use it many times. It reduces complexity of a big program and optimizes the code.

CPP Functions 1 

Declaration of a function

The syntax of creating function in C++ language is given below:

  1. return_type function_name(data_type parameter...)  
  2. {    
  3. //code to be executed    
  4. }  

C++ Function Example

Let's see the simple example of C++ function.

  1. #include <iostream>  
  2. using namespace std;  
  3. void func() {    
  4.    static int i=0; //static variable    
  5.    int j=0; //local variable    
  6.    i++;    
  7.    j++;    
  8.    cout<<"i=" << i<<" and j=" <<j<<endl;    
  9. }    
  10. int main()  
  11. {  
  12.  func();    
  13.  func();    
  14.  func();    
  15. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

Call by value and call by reference in C++

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

CPP Call by value and call by reference in cpp 1

Let's understand call by value and call by reference in C++ language one by one.


Call by value in C++

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in C++ language by the example given below:

  1. #include <iostream>  
  2. using namespace std;  
  3. void change(int data);  
  4. int main()  
  5. {  
  6. int data = 3;  
  7. change(data);  
  8. cout << "Value of the data is: " << data<< endl;  
  9. return 0;  
  10. }  
  11. void change(int data)  
  12. {  
  13. data = 5;  
  14. }  

Output:

Value of the data is: 3

Call by reference in C++

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments share the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in C++ language by the example given below:

  1. #include<iostream>  
  2. using namespace std;    
  3. void swap(int *x, int *y)  
  4. {  
  5.  int swap;  
  6.  swap=*x;  
  7.  *x=*y;  
  8.  *y=swap;  
  9. }  
  10. int main()   
  11. {    
  12.  int x=500, y=100;    
  13.  swap(&x, &y);  // passing value to function  
  14.  cout<<"Value of x is: "<<x<<endl;  
  15.  cout<<"Value of y is: "<<y<<endl;  
  16.  return 0;  
  17. }    

Output:

Value of x is: 100
Value of y is: 500   

Difference between call by value and call by reference in C++

No.Call by valueCall by reference
1A copy of value is passed to the functionAn address of value is passed to the function
2Changes made inside the function is not reflected on other functionsChanges made inside the function is reflected outside the function also
3Actual and formal arguments will be created in different memory locationActual and formal arguments will be created in same memory location

Anurag Rana Educator CSE/IT

Comments

Popular posts from this blog

Standard and Formatted Input / Output in C++

The C++ standard libraries provide an extensive set of input/output capabilities which we will see in subsequent chapters. This chapter will discuss very basic and most common I/O operations required for C++ programming. C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a keyboard, a disk drive, or a network connection etc. to main memory, this is called   input operation   and if bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc., this is called   output operation . Standard Input and Output in C++ is done through the use of  streams . Streams are generic places to send or receive data. In C++, I/O is done through classes and objects defined in the header file  <iostream> .  iostream  stands for standard input-output stream. This header file contains definitions to objects like  cin ,  cout , etc. /O Library Header Files There are...

Genetic Algorithm: Population, Fitness Function, Parent Selection, Cross over, Mutation

Genetic Algo Population Population is a subset of solutions in the current generation. It can also be defined as a set of chromosomes. There are several things to be kept in mind when dealing with GA population − The diversity of the population should be maintained otherwise it might lead to premature convergence. The population size should not be kept very large as it can cause a GA to slow down, while a smaller population might not be enough for a good mating pool. Therefore, an optimal population size needs to be decided by trial and error. The population is usually defined as a two dimensional array of –  size population, size x, chromosome size . Population Initialization There are two primary methods to initialize a population in a GA. They are − Random Initialization  − Populate the initial population with completely random solutions. Heuristic initialization  − Populate the initial population using a known heuristic for the problem. It has been observed that the e...

C++ (Object and Class)

The major purpose of C++ programming is to introduce the concept of object orientation to the C programming language. Object Oriented Programming is a paradigm that provides many concepts such as  inheritance, data binding, polymorphism etc. The programming paradigm where everything is represented as an object is known as truly object-oriented programming language.  Smalltalk  is considered as the first truly object-oriented programming language. OOPs (Object Oriented Programming System) Object  means a real word entity such as pen, chair, table etc.  Object-Oriented Programming  is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts: Object Class Inheritance Polymorphism Abstraction Encapsulation C++ Object In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc. In other words, object is an ent...