fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. void buyCoffee(double& totSmall, double& totMedium, double& totLarge)
  5. {
  6. totSmall = 5;
  7. totMedium = 10;
  8. totLarge = 15;
  9. }
  10.  
  11. void print(const std::string& header, double totalSmall, double totalMedium, double totalLarge)
  12. {
  13. std::cout << header << "\n";
  14. std::cout << "totalSmall = " << totalSmall
  15. << ", totalMedium = " << totalMedium
  16. << ", totalLarge = " << totalLarge << "\n";
  17. }
  18.  
  19. int main()
  20. {
  21. // This uses explicit references as you had in your example with
  22. // a correction to the second and third variables
  23. {
  24. double totalSmall = 0, totalMedium = 0, totalLarge = 0;
  25.  
  26. print("Before: ", totalSmall, totalMedium, totalLarge);
  27.  
  28. double& totSmall = totalSmall, & totMedium = totalMedium, & totLarge = totalLarge;
  29. buyCoffee(totSmall, totMedium, totLarge);
  30.  
  31. print("After: ", totalSmall, totalMedium, totalLarge);
  32. }
  33.  
  34. // This just passes the variables to the function
  35. // Since the function accepts them by reference it modifies
  36. // the original variable inside the function
  37. {
  38. double totalSmall = 0, totalMedium = 0, totalLarge = 0;
  39.  
  40. print("Before: ", totalSmall, totalMedium, totalLarge);
  41.  
  42. buyCoffee(totalSmall, totalMedium, totalLarge);
  43.  
  44. print("After: ", totalSmall, totalMedium, totalLarge);
  45. }
  46. }
  47.  
Success #stdin #stdout 0.01s 5552KB
stdin
Standard input is empty
stdout
Before: 
totalSmall = 0, totalMedium = 0, totalLarge = 0
After: 
totalSmall = 5, totalMedium = 10, totalLarge = 15
Before: 
totalSmall = 0, totalMedium = 0, totalLarge = 0
After: 
totalSmall = 5, totalMedium = 10, totalLarge = 15