I want to swap 2 integers in a function, but cant do it without passing the parameters by reference, but when I use the same code inside main(), it works without using the integer’s memory address
passing parameters as reference
#include <iostream>
using namespace std;
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "n";
cout << firstNum << secondNum << "n";
// Call the function, which will change the values of firstNum and secondNum
swapNums(firstNum, secondNum);
cout << "After swap: " << "n";
cout << firstNum << secondNum << "n";
return 0;
}
/*output
Before swap:
1020
After swap:
2010
*/
but when I pass the parameters as integers, the numbers don’t swap
passing parameters as integers
#include <iostream>
using namespace std;
void swapNums(int x, int y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "n";
cout << firstNum << secondNum << "n";
swapNums(firstNum, secondNum);
cout << "After swap: " << "n";
cout << firstNum << secondNum << "n";
return 0;
}
/*output
Before swap:
1020
After swap:
1020
*/
and again, if I don’t use a function and write the code inside the main block, it works without any problem.
not using function and running the code in main() block
#include <iostream>
using namespace std;
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "n";
cout << firstNum << secondNum << "n";
int z = firstNum;
firstNum = secondNum;
secondNum = z;
cout << "After swap: " << "n";
cout << firstNum << secondNum << "n";
return 0;
}
/*output
Before swap:
1020
After swap:
2010
*/
thank you for helping me and appreciate your patience to read my first question in stack overflow