I’m starting with developing, sorry about this newbie question.
I need to create a function that swap values between 2 vars.
I have wrote this code, but no changes are made in vars, What should I change? What is my mistake?
#include <iostream>
using namespace std;
void swap_values( int x, int y);
int main(void) {
int a,b;
a = 2;
b = 5;
cout << "Before: " << a << " " << b << endl;
swap_values( a,b );
cout << "After: " << a << " " << b << endl;
}
void swap_values( int x, int y ){
int z;
z = y;
y = x;
x = z;
}
You need to pass the variables by reference:
pass-by-valueandpass-by-referenceare key concepts in major programming languages. In C++, unless you specify by-reference, apass-by-valueoccurs.It basically means that it’s not the original variables that are passed to the function, but copies.
That’s why, outside the function, the variables remained the same – because inside the functions, only the copies were modified.
If you pass by reference (
int& x, int& y), the function operates on the original variables.