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

JAVA Scrollbar, MenuItem and Menu, PopupMenu

ava AWT Scrollbar The  object  of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a  GUI  component allows us to see invisible number of rows and columns. AWT Scrollbar class declaration public   class  Scrollbar  extends  Component  implements  Adjustable, Accessible   Java AWT Scrollbar Example import  java.awt.*;   class  ScrollbarExample{   ScrollbarExample(){               Frame f=  new  Frame( "Scrollbar Example" );               Scrollbar s= new  Scrollbar();               s.setBounds( 100 , 100 ,  50 , 100 );               f.add(s);               f.setSize( 400 , 400 );               f.setLayout( null );               f.setVisible( true );   }   public   static   void  main(String args[]){           new  ScrollbarExample();   }   }   Output: Java AWT Scrollbar Example with AdjustmentListener import  java.awt.*;   import  java.awt.event.*;   class  ScrollbarExample{        ScrollbarExample(){               Frame f=  new  Frame( "Scro

Difference between net platform and dot net framework...

Difference between net platform and dot net framework... .net platform supports programming languages that are .net compatible. It is the platform using which we can build and develop the applications. .net framework is the engine inside the .net platform which actually compiles and produces the executable code. .net framework contains CLR(Common Language Runtime) and FCL(Framework Class Library) using which it produces the platform independent codes. What is the .NET Framework? The Microsoft .NET Framework is a platform for building, deploying, and running Web Services and applications. It provides a highly productive, standards-based, multi-language environment for integrating existing investments with next-generation applications and services as well as the agility to solve the challenges of deployment and operation of Internet-scale applications. The .NET Framework consists of three main parts: the common language runtime, a hierarchical set of unified class librari

C++ this Pointer, static, struct and Enumeration

C++ this Pointer In C++ programming,  this  is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C++. It can be used  to pass current object as a parameter to another method. It can be used  to refer current class instance variable. It can be used  to declare indexers. C++ this Pointer Example Let's see the example of this keyword in C++ that refers to the fields of current class. #include <iostream>    using   namespace  std;   class  Employee {       public :           int  id;  //data member (also instance variable)               string name;  //data member(also instance variable)            float  salary;          Employee( int  id, string name,  float  salary)             {                   this ->id = id;                  this ->name = name;                  this ->salary = salary;            }             void  display()             {                 cout<<id<< "  " <<name<&