Website For Developers

Function Parameters in C++




Pass by Value in C++


Example of Pass by value in C++

//Program to find minimum value
#include<iostream>
#include<conio.h>
using namespace std;

int min (int a, int b);
int main() {

  int x, y;
  cout<<"Please Enter the first Number: "<<endl;
  cin>>x;
  cout<<"Please Enter the secong Number: "<<endl;
  cin>>y;
  min(x,y);
  getch();
  return 0;
}

int min(int a, int b) {
  if(a<b) {
    cout<<"First number is minimum. And its value is: "<<a<<endl;
  }
  else if (b<a) {
    cout<<"Second number is minimum. And its value is: "<<b<<endl;
  }
  else {
    cout<<"Both numbers are equal "<<endl;
  }
}

Output

Please enter the first number: 107
Please enter the second number: 291
First number is minimum. And its value is: 107



Second Example of Pass by value in C++

#include<iostream>
#include<conio.h>
using namespace std;
void change (int a, int b);
int main() {
  int a, b;
  a = 10;
  b = 5;
  cout<<"Before! "<<endl;
  cout<<"Value of a = "<<a<<endl;
  cout<<"Value of b = "<<b<<endl;
  change(a, b);
  cout<<"After! "<<endl;
  cout<<"Value of a = "<<a<<endl;
  cout<<"Value of b = "<<b<<endl;
  getch();
  return 0;
}

void change(int a , int b) {
    a = 25;
    b = 50;
}

Output

Before!
Value of a = 10
Value of b = 5
After!
Value of a = 10
Value of b = 5




Pass by Reference in C++


Example of Pass by Reference in C++

//Program to sum three integer values
#include<iostream>
#include<conio.h>
using namespace std;
int sum (int &v1, int &v2, int &v3);
int main() {
  int value1, value2, value3;
  cout<<"Enter first value: "<<endl;
  cin>>value1;
  cout<<"Enter second value: "<<endl;
  cin>>value2;
  cout<<"Enter third value: "<<endl;
  cin>>value3;
  sum(value1, value2, value3);
  getch();
  return 0;
}

int sum(int &v1 , int &v2, int &v3) {
  int sum = v1+v2+v3;
  cout<<"Total is: "<<sum;
}

Output

Enter first value: 32
Enter second value: 29
Enter third value: 11
Total is: 72


Second Example of Pass by Reference in C++

#include<iostream>
#include<conio.h>
using namespace std;
void change (int &a, int &b);
int main() {
  int a, b;
  a = 10;
  b = 5;
  cout<<"Before!"<<endl;
  cout<<"Value of a = "<<a<<endl;
  cout<<"Value of b = "<<b<<endl;
  change(a, b);
  cout<<"After!"<<endl;
  cout<<"Value of a = "<<a<<endl;
  cout<<"Value of b = "<<b<<endl;
  getch();
  return 0;
}

void change(int &a , int &b){
  a = 25;
  b = 50;
}

Output

Before!
Value of a = 10
Value of b = 5
After!
Value of a = 25
Value of b = 50