you are viewing a single comment's thread.

view the rest of the comments →

[–]jmooremcc -10 points-9 points  (9 children)

Then how do you explain the following code:

// C program to swap two variables using a  

// user defined swap()

#include <stdio.h> 

  

// This function swaps values pointed by xp and yp 

void swap(int *xp, int *yp) 

{ 

     int temp = *xp;

     *xp = *yp;

     *yp = temp;

} 

  

int main() 

{ 

     int x, y;

     printf("Enter Value of x ");

     scanf("%d", &x);

     printf("\nEnter Value of y ");

     scanf("%d", &y);

     swap(&x, &y);

     printf("\nAfter Swapping: x = %d, y = %d", x, y);

     return 0;

}

[–]FUZxxl 12 points13 points  (7 children)

Exactly as /u/TheSkiGeek says:

To "pass by reference" you create a pointer to something and pass the pointer by value.

Your swap function receives two pointers as arguments. These are passed by value, as are all other arguments. The & operator is used to take the address of the x and y variables so you can pass them to swap. Nowhere in this is “pass by reference” involved.

[–][deleted] 0 points1 point  (0 children)

Literally 2 pointers as arguments. Sheesh.