fork download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. void swap1(int a, int b){ // passing by value
  6. int c = a;
  7. a = b;
  8. b = c;
  9. }
  10.  
  11. void swap2(int* a, int* b){ // pointer method (requires passing memory address (&var) instead of var)
  12. int c = *a; // store value at a into c
  13. *a = *b; // assign b's value to a's value
  14. *b = c; // assign c to b's value
  15. }
  16.  
  17. void swap3(int& a, int& b){ // pass by reference
  18. int c = a;
  19. a = b;
  20. b = c;
  21. }
  22.  
  23. int main(){
  24. int a = 5;
  25. int b = 3;
  26. swap1(a, b); // doesn't swap
  27. cout << "a=" << a << ", b=" << b << endl;
  28.  
  29. swap2(&a, &b); // swaps with pointers
  30. cout << "a=" << a << ", b=" << b << endl;
  31.  
  32. swap3(a, b); // swaps with references
  33. cout << "a=" << a << ", b=" << b << endl;
  34.  
  35. int* ra = &a;
  36. int* rb = &b;
  37. int y = *ra;
  38. (*ra)++;
  39. y = *ra;
  40.  
  41. return 0;
  42. }
Success #stdin #stdout 0.02s 2724KB
stdin
Standard input is empty
stdout
a=5, b=3
a=3, b=5
a=5, b=3