[Solved] Trying to understand a function to swap two int values


Let’s try to explain *x = *y; without using the word “dereference”:

  • *x represents the integer object pointed to by x. As it is the left operand of the assignment, it means that this integer object is going to be updated.
  • *y represents the integer object pointed to by y. As it is the right operand of the assignment, it means that the content of the integer object (i.e. its value) is going to be used.
  • *x=*y updates the integer object pointed to by x with the integer object pointed to by y.

Note: To clearly distinguish pointers from other types in the code, I suggest you to change naming as follows, using a prefix like p_ for pointer variables for example:

 1 void swap (int* p_x, int* p_y){
 2    int temp = *p_x; 
 3    *p_x = *p_y;
 4    *p_y = temp;
 5 }
 6
 7 int x,y;
 8 x = 1;
 9 y = 2;
10 swap(&x,&y)

4

solved Trying to understand a function to swap two int values