Call by Value and Call by Reference

Total Post:113

Points:791
 233  View(s)
Ratings:
Rate this:

Explain Call by Value and Call by Reference through stack in data structure ?

  1. Post:140

    Points:984
    Re: Call by Value and Call by Reference

    Call by value:

    the called function creates a new set of variables in stack is called call by value whch is copies the values of the arguments into method. 

    void swap(int x, int y) 
    {
         int z;
         z = x;
         x = y;
         y = z;
         printf("Swapped values are a = %d and b = %d", x, y);
     }
    int main (int argc, char *argv[])
    {
         int a = 10, b = 6;
         printf("Original values are a = %d and b = %d", a, b);
         swap(a, b);
         printf("The values after swap are a = %d and b = %d", a, b);
    }

    - push value of b

    - push value of a

    - save return address

    - call function

    Call by reference: 

    instead of passing values to the function by a pointers to the original variables are passed this method known as call by reference method. 

    void swap(int *x, int *y) 
    {
         int z;
        z = *x;
         *x = *y;
         *y = z;
         printf("Swapped values are a = %d and b = %d", *x, *y);
    }
    int main (int argc, char *argv[])
    {
         int a = 10, b = 6;
         printf("Original values are a = %d and b = %d", a, b);
         swap(&a, &b);
         printf("The values after swap are a = %d and b = %d", a, b);
     }

    - push address of b

    - push address of a

    - save return address

    - call function

Answer