Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

c++ call by value vs call by reference

//calling by value
//the increment function and the main function has two different variables in two
//different addresses in the memory

//In other words, we pass the value of the variable to the function
#include <iostream>
using namespace std;
void increment(int n){
    n++;
   cout<<"In function: "<<n<<endl; 
}

int main()
{
   int x=5;
   increment(x);
   cout<<"In main: "<<x<<endl;	//No change occurs to the variable in the main
   
}

//calling by refrence
//the increment function points to the address of the variable in the main function
//In other words, we pass the variable itself to the function

#include <iostream>
using namespace std;
void increment(int &n){
    n++;
   cout<<"In function: "<<n<<endl; 
}

int main()
{
   int x=5;
   increment(x);
   cout<<"In main: "<<x<<endl;
   
}
 
PREVIOUS NEXT
Tagged: #call #call #reference
ADD COMMENT
Topic
Name
7+8 =