Advertisement
DrAungWinHtut

swap.cpp

Oct 10th, 2024
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.50 KB | None | 0 0
  1. #include<iostream>
  2. void swap(int x, int y);
  3. void swap2(int* x, int* y); //call by reference
  4.  
  5. int main()
  6. {
  7.     int i = 2;
  8.     int j = 4;
  9.     swap(i, j);
  10.     std::cout << "i = " << i << " , j = " << j << std::endl;
  11.     swap2(&i, &j);
  12.     std::cout << "i = " << i << " , j = " << j << std::endl;
  13.  
  14.     return 0;
  15. }
  16.  
  17.  
  18. void swap(int x, int y) //call by value
  19. {
  20.     int temp = x;
  21.     x = y;
  22.     y = temp;
  23. }
  24.  
  25. void swap2(int* x, int* y) //call by reference
  26. {
  27.     int temp = *x; //dereferencing x->value
  28.     *x = *y;
  29.     *y = temp;
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement