call by value and call by reference in c++

 #include<iostream>

using namespace std;

// int sum(int a, int b){
//     int c;
//     c = a + b;
//     return c;
// }

void swap(int a, int b){  /*temp  a  b*/
    int temp = a;          /* 5    5  7*/
    a = b;                 /* 5    7  7*/    //ye ek value exchange krne ka tarika hai
    b=temp;                /* 5    7  5*/    
}

/*yaha x aur y (actual arguments) ki value copy hui a aur b m but and vo exchange hue
jisse x and y kuch frk nhi pdega*/

/********CALL BY REFERENCE USING POINTERS******* */

void swapPointer(int* a, int* b){ //int* mtlb address liya hai
    int temp = *a; //*a mtlb dereference kiya hai (value at address a)
    *a = *b;
    *b = temp;
}

/********CALL BY REFERENCE USING c++ REFERENCE VARIABLES******* */

// // void swapReferenceVar(int &a, int &b){ //int* mtlb address liya hai
// //     int temp = a; //*a mtlb dereference kiya hai (value at address a)
// //     a = b;
// //     b = temp;
// }

//this will swap a and b because a point krra x ko memory m and b point krra y ko memory m

int & swapReferenceVar(int &a, int &b){ //int* mtlb address liya hai
    int temp = a; //*a mtlb dereference kiya hai (value at address a)
    a = b;
    b = temp;
    return a;
}

//this is function is returning a reference "a" which is pointing x
//ye pura x a referemnce return krega which is equal to 57, so ka value change hojaega

int main(){
 
    // int num1, num2;
    // cout<<"enter the value of num 1 "<<endl;
    // cin>>num1;
    // cout<<"enter the value of num2 "<<endl;
    // cin>>num2;
    // cout<<"the sum of "<<num1<<" and "<<num2<<" is "<<sum(num1, num2);

    int x=5, y=7;

    cout<<"the value of x was "<<x<<" the value of y was "<<y<<endl;
    // swap(x,y);//this will not swap a and b
    // swapPointer(&x, &y); //&x mtlb lelo address x ka, this will swap a and b
    // swapReferenceVar(x, y); //this will swap a and b using c++ reference variables
    swapReferenceVar(x, y) = 57;
    cout<<"the value of x is "<<x<<" the value of y is "<<y<<endl;

    return 0;
}

Comments

Popular posts from this blog

Function Overloading in C++

oops recall, basic operations and nesting of member functions

OBJECT ORIENTED PROGRAMMING, classes public and private access modifiers (syntax)