Modifying data in C++

There are two ways to pass value or data to functions/objects in C++ language: call by value and call by reference. The original value is not modified in the call by value but it is modified in the call by reference.

Untitled-2022-08-13-2153(3).png

By Value

When an object is passed by value, the function creates its own copy of an object and works with its own copy. Therefore any change made to the object inside the function does not affect the original object.

    #include <iostream>  
    using namespace std;  
    void change(int data);  
    int main()  
    {  
    int data = 3;  
    change(data);  
    cout << "Value of the data is: " << data<< endl;  
    return 0;  
    }  
    void change(int data)  
    {  
    data = 5;  
    }

By Reference

When an object is padded by reference, its memory address is passed to the function so that function works directly on the original object used in the function call.

    #include<iostream>  
    using namespace std;    
    void swap(int *x, int *y)  
    {  
     int swap;  
     swap=*x;  
     *x=*y;  
     *y=swap;  

    }  
    int main()   
    {    
     int x=500, y=100;    
     swap(&x, &y);  // passing value to function  
     cout<<"Value of x is: "<<x<<endl;  
     cout<<"Value of y is: "<<y<<endl;  
     return 0;  
    }

Untitled-2022-08-13-2153(4).png

Difference between Modifying data By value and By Reference.

Untitled-2022-08-13-2153(5).png