//This tut contains Call by Value & Call by Reference in C++ 
#include<iostream>
using namespace std;
int sum(int a , int b){
    int c=a+b;
    return c;
}
//--------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------
// This will not swap numbers.
void swap(int a,int b){
    int temp=a;
    a=b;
    b=temp;
}
// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
//Call by reference using pointers -->
// This will swap numbers
void swapPointer(int* a, int* b){
    int temp=*a;
    *a= *b;
    *b= temp;
}
// ---------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------
//Call by reference using C++ reference Variables -->
//This will swap numbers.
void swapreference(int &a ,int &b){
    int temp=a;
    a=b;
    b=temp;
}
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
int main(){
    int x=4, y= 5;
    cout<<"The sum of 2 numbers is :"<< sum(4,5) <<endl;
    cout<<"The value of x  before swapping is :"<<x<<endl;
    cout<<"The value of y  before swapping is :"<<y<<endl;
    //swap(x,y);  ---> This is not working 
    //swapPointer(&x,&y); //---> This  will swaps value of numbers -->This will swap a and b using pointer reference
    swapreference(x,y); //This will swap a and b using reference variables
    cout<<"The value of x  after swapping is :"<<x<<endl;
    cout<<"The value of y  after swapping is :"<<y<<endl;
    return 0;
}
 
 
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.