fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. // --- Call by Value ---
  5. int sumByValue(int a, int b) {
  6. return a + b; // works on copies of a and b
  7. }
  8.  
  9. // --- Call by Address (using pointers) ---
  10. void swapByAddress(int *x, int *y) {
  11. int temp = *x;
  12. *x = *y;
  13. *y = temp;
  14. }
  15.  
  16. // --- Call by Reference ---
  17. void applyMultiplier(int &balance1, int &balance2, int multiplier) {
  18. balance1 *= multiplier;
  19. balance2 *= multiplier;
  20. }
  21.  
  22. int main() {
  23. int amount1, amount2;
  24. cout << "Enter two amounts: ";
  25. cin >> amount1 >> amount2;
  26.  
  27. // Call by Value
  28. int sum = sumByValue(amount1, amount2);
  29. cout << "\n[Call by Value] Sum of amounts = " << sum << endl;
  30.  
  31. // Call by Address
  32. cout << "\n[Call by Address] Before swap: amount1 = " << amount1 << ", amount2 = " << amount2 << endl;
  33. swapByAddress(&amount1, &amount2);
  34. cout << "After swap: amount1 = " << amount1 << ", amount2 = " << amount2 << endl;
  35.  
  36. // Call by Reference
  37. int multiplier;
  38. cout << "\nEnter multiplier to apply: ";
  39. cin >> multiplier;
  40. applyMultiplier(amount1, amount2, multiplier);
  41. cout << "[Call by Reference] After applying multiplier: amount1 = " << amount1 << ", amount2 = " << amount2 << endl;
  42.  
  43. return 0;
  44. }
Success #stdin #stdout 0.01s 5320KB
stdin
100 200
3
stdout
Enter two amounts: 
[Call by Value] Sum of amounts = 300

[Call by Address] Before swap: amount1 = 100, amount2 = 200
After swap: amount1 = 200, amount2 = 100

Enter multiplier to apply: [Call by Reference] After applying multiplier: amount1 = 600, amount2 = 300