Cycle 05
Functions, Recursion, Parameter Passing & Classes
Swap Numbers using Pass-by-Value, Pass-by-Reference, and Pass-by-Pointer
Problem Statement
Write a Turbo C++ program to demonstrate the 3 parameter passing methods in C++: (1) Pass-by-Value, (2) Pass-by-Reference using reference variables (&), and (3) Pass-by-Pointer using memory addresses (*).
#include <iostream.h>
#include <conio.h>
// 1. Pass-by-Value (changes do NOT affect caller arguments)
void swapByValue(int a, int b) {
int temp = a;
a = b;
b = temp;
}
// 2. Pass-by-Reference (aliases direct memory of caller arguments)
void swapByReference(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
// 3. Pass-by-Pointer (dereferences memory addresses)
void swapByPointer(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void main() {
int x = 10, y = 20;
clrscr();
cout << "Initial Values: x = " << x << ", y = " << y << endl;
// Call by Value
swapByValue(x, y);
cout << "\nAfter swapByValue(x, y): x = " << x << ", y = " << y << " (Unchanged)" << endl;
// Call by Reference
swapByReference(x, y);
cout << "After swapByReference(x, y): x = " << x << ", y = " << y << " (Swapped!)" << endl;
// Call by Pointer
swapByPointer(&x, &y);
cout << "After swapByPointer(&x, &y): x = " << x << ", y = " << y << " (Swapped back!)" << endl;
getch();
}
Question 1 of 3