+ 2

how does this function work?

I tryed to swap two numbers, but it didnt work at all. I am not sure about return here. Can someone explain to me how to swap it? :) #include <iostream> using namespace std; int swap(int a, int b) { int c; c = a; a = b; b = c; return a, b; //is it right? } int main() { int m = 29, n = 42; //declaring variables cout << m <<", " << n <<endl; //29, 42 swap(m, n); //using our function cout << m <<", " << n <<endl; //29, 42 return 0; }

27th Jul 2017, 8:31 AM
Игорь Литвин
Игорь Литвин - avatar
2 Answers
+ 8
You can't return two integer values at once. Only one value will be returned. You want to use a function to swap the variables by making changes to the original variables, and not to return stuff back to main, so you will want to use void function (no return value) and pass your variables by reference. #include <iostream> using namespace std; void swap(int& a, int& b) { int c; c = a; a = b; b = c; } int main() { int m = 29, n = 42; cout << m <<", " << n <<endl; swap(m, n); cout << m <<", " << n <<endl; return 0; }
27th Jul 2017, 8:35 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
Hatsy Rei, thank you
27th Jul 2017, 8:42 AM
Игорь Литвин
Игорь Литвин - avatar