Call By Value & Call By Reference in C++.

Calling Of A Function

What is Call by Value method?
  • Call by value method copies the value of an argument into that function's formal parameter. Consequently, changes made to the main function parameter do not influence the argument.
  • In this process of transferring parameter, values of real parameters are copied to the formal parameters of the function, and the parameters are stored through different locations of the memory. 
  • So any changes made within functions are not expressed in the caller's actual parameters.

What is Call by Reference method?
Call by reference method copies the address of an argument into the formal parameter. In this method, the address is used to access the actual argument used in the function call. It means that changes made in the parameter alter the passing argument.

In this method, the memory allocation is the same as the actual parameters. All the operation in the function are performed on the value stored at the address of the actual parameter, and the modified value will be stored at the same address.
the function can be called using either of the following methods:
i) call by value 
ii) call by reference

Call By Value

In call by value method, the called function creates its own copies of original values sent to it. Any changes, that are made, occur on the function’s copy of values and are not reflected back to the calling function.

Call By Reference

In call be reference method, the called function accesses and works with the original values using their references. Any changes, that occur, take place on the original values are reflected back to the calling code.
Consider the following program which will swap the value of two variables.
www.mskuthar.blogspot.com

Example of a Call by Value method
void main() {
        int a = 10,
        void increment(int);
        Cout << "before function calling" << a;
        increment(a);
        Cout << "after function calling" << a;
        getch();

        void increment(int x) {
            int x = x + 1;
            Cout << "value is" << x;
        }

Output:-

before function calling 10
value is 11
after function calling 1-0

Example of a Call by Value method
void main() {
        int a = 10,
        void increment(int);
        Cout << "before function calling" << a;
        increment(a);
        Cout << "after function calling" << a;
        getch();

        void increment(int x) {
            int x = x + 1;
            Cout << "value is" << x;
        }
Output:-

before function calling 10
value is 11
after function calling 1-0

Difference between Call by Value and Call by 
Reference

www.mskuthar.blogspot.com

Post a Comment

Previous Post Next Post