Search
 
SCRIPT & CODE EXAMPLE
 

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;
   
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: c++ typedef 
Cpp :: how to get length of a file in c++ 
Cpp :: c++ sort vector 
Cpp :: 2d vector c++ size 
Cpp :: C++ Find the sum of first n Natural Numbers 
Cpp :: Rick Astley - Never Gonna Give You Up 
Cpp :: arguments to a class instance c++ 
Cpp :: conditional variable c++ 
Cpp :: getline cpp 
Cpp :: how to declare a function in c++ 
Cpp :: min heap and max heap using priority queue 
Cpp :: how to get an element in a list c++ 
Cpp :: find primes in cpp 
Cpp :: how to iterate throguh a string in c++ 
Cpp :: when was c++ created 
Cpp :: strlen in c++ 
Cpp :: int to hex arduino 
Cpp :: divide and conquer based algorithm to find maximum and minimum of an array 
Cpp :: c++ remove last character from string 
Cpp :: length of array in cpp 
Cpp :: what is c++ standard library 
Cpp :: map declaration c++ 
Cpp :: opencv open image c++ 
Cpp :: how to read files in c++ 
Cpp :: c++ basic snippet 
Cpp :: priority queue smallest first 
Cpp :: remove element from vector 
Cpp :: notepad++ 
Cpp :: c++ looping through a vector 
Cpp :: length of number c++ 
ADD CONTENT
Topic
Content
Source link
Name
3+1 =