fork download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. // this function increments the actual variable
  6. // passed as an argument because it is passed
  7. // as reference (with & in front of its name)
  8.  
  9. void correct_increment(int &i)
  10. {
  11. i++;
  12. }
  13.  
  14. // this function does increment only a copy
  15. // of the input argument, so the modifications
  16. // are lost once the function terminates
  17.  
  18. void wrong_increment(int i)
  19. {
  20. i++;
  21. }
  22.  
  23. // main function
  24.  
  25. int main()
  26. {
  27. int i=0;
  28.  
  29. // call wrong increment 3 times
  30.  
  31. wrong_increment(i);
  32. wrong_increment(i);
  33. wrong_increment(i);
  34.  
  35. // print out the result
  36.  
  37. cout << "value of i after 3 calls to wrong_increment: " << i << endl;
  38. cout << endl;
  39.  
  40. // call wrong increment 3 times
  41.  
  42. correct_increment(i);
  43. correct_increment(i);
  44. correct_increment(i);
  45.  
  46. // print out the result
  47.  
  48. cout << "value of i after 3 calls to correct_increment: " << i << endl;
  49.  
  50. // return 0 from the main
  51.  
  52. return 0;
  53. }
Success #stdin #stdout 0.02s 2680KB
stdin
Standard input is empty
stdout
value of i after 3 calls to wrong_increment: 0

value of i after 3 calls to correct_increment: 3