DEV Community

Hmm
Hmm

Posted on

Parameter Passing

In C++ there are 3 ways to pass parameter to function -

  1. Pass by Value
  2. Pass by Reference
  3. Pass by Pointers

I will discuss one of them here.

Pass by Value

In pass by value , each function have their own local variables and the variables have their own local scope.

#include <iostream>
using namespace std;

void swap( int a , int b){
int temp = a;
a = b; 
b = temp;
cout<< "Values inside swap function , a is "<<a<<" and b is "<<b<<endl;
}

int main(){
int a = 10 ;
int b = 20;
cout<<"Before swapping a is "<<a<<" and b is "<<b<<endl;
swap(a,b);
cout<<"After swapping a is "<<a<<" and b is "<<b<<endl;

return 0;
}


Enter fullscreen mode Exit fullscreen mode

Here if we run this code , we'll find that the values are only swapped in the swap function but when the activation record of swap function is delete when code control comeback to main function , the values of "a" and "b" are unchanged . That's because both "main" and "swap" function have their own "a" and "b" variables.

Pass by value is a good choice when we want to return the result without changing the value of original variables . For example :-

int add(int a, int b){
return a+b;
}
Enter fullscreen mode Exit fullscreen mode

We will learn Pass by Reference next time.

Top comments (0)