Swapping two variables
1. Swapping Two Numbers Using Call by Value
#include <iostream>
// Function to swap two numbers (ineffective with Call by Value)
void swapByValue(int x, int y) {
int temp = x;
x = y;
y = temp;
// Values are swapped only within the scope of this function
std::cout << "Inside swapByValue function: x = " << x << ", y = " << y << std::endl;
}
int main() {
int a = 10;
int b = 20;
std::cout << "Before swapByValue: a = " << a << ", b = " << b << std::endl;
swapByValue(a, b); // Passing a and b by value
std::cout << "After swapByValue: a = " << a << ", b = " << b << std::endl;
return 0;
}2. Swapping Two Numbers Using Call by Reference
3. Swapping Two Numbers Using Call by Reference (Alternative with References)
Comparison: Call by Value vs. Call by Reference
Summary
Last updated