ccall-by-value

Call by value can change the value for main program


Consider the following programs:

void f2 ( int * a, int * b) {   
               int c; 
               c = * a;
               *a = *b;
               *b = c; 
} 
int main () { 
        int a = 4, b = 5, c = 6; 
        f2 (&b, &c); 
        printf ("%d", c - a - b);  
 }

Here the values of b and c are getting swapped.

And another code is:

# include <stdio.h>
void mystery (int *ptra, int *ptrb) {  
     int *temp; 
     temp = ptrb;  
     ptrb = ptra; 
     ptra = temp; 
} 
int main () { 
    int a = 2016, b=0, c= 4, d = 42; 
    mystery (&a, &b);
    if (a < c) 
          mystery (&c, &a); 
    mystery (&a, &d); 
    printf("%d\n", a); 
}

Here, though same type of function call is there, values of any variable in main() program does not changed.

As we know, there is no call by reference in C code. So, my question is, though there are same type of function call in both the program, then why one is swapping the values of variable and another cannot swap??

In the second program pointer is swapping means address are also swapping. Right?? But it doesn't affect on value. While in 1st program , address and pointer is swapped and at the mean time values also swapped. But Why??

I also want to know, where call by value, can change the value of main() program (with or without return function)??


Solution

  • In f2 in the first program, pointers are being dereferenced to change what those pointers point to so that b and c in the main function are modified. In contrast, mystery in the second program is only swapping the values of the local variables ptra and ptrb which has no effect on the variables in main.

    So this:

    ptrb = ptra; 
    

    Assigned the value of one pointer to another (which are both local to msytery), while this:

    *a = *b;
    

    Changes the value of what one pointer points to to the value of what another pointer points to, namely a and b in main.

    Another way to think of this is with houses and their residents:

        ______        _____         ______       ______
       /______\      /______\      /______\     /______\
     2 |Smith |    4 |Jones |    6 | Bond |   8 | Solo |
       --------      --------      --------     --------
    

    The first program is saying "swap the residents of two houses":

        ______        _____         ______       ______
       /______\      /______\      /______\     /______\
     2 |Smith |    4 | Bond |    6 |Jones |   8 | Solo |
       --------      --------      --------     --------
    

    While the second is saying "swap the numbers on the houses":

        ______        _____         ______       ______
       /______\      /______\      /______\     /______\
     2 |Smith |    6 |Jones |    4 | Bond |   8 | Solo |
       --------      --------      --------     --------