c++ - Call by reference function and syntax -
the code sorts 3 numbers in ascending order. but, swap function has been invoked reference. why must sort function invoked reference ? question swap function has been invoked reference. so, why need sort function reference ? i'm confused. secondly, cout << endl, doesn't give error so, i've pressed wrongly comma. how come ?
#include <iostream> using namespace std; void swap ( int& a, int& b ); void sort ( int a, int b, int c ); int main() { int num1, num2, num3; cout << "enter first number => "; cin >> num1; cout << "enter second number => "; cin >> num2; cout << "enter third number => "; cin >> num3; cout << endl, cout << "before sorting numbers\n" << num1 << " " << num2 << " " << num3 << endl; sort( num1, num2, num3 ); cout << "after sorting numbers\n" << num1 << " " << num2 << " " << num3 << endl; return 0; } void swap ( int& a, int& b ) { int temp = a; = b; b = temp; } void sort ( int a, int b, int c ) { //void sort ( int& a, int& b, int& c ) if (a > b) swap(a, b); if (a > c) swap(a, c); if (b > c) swap(b, c); }
when call sort function, 3 new variables created in scope of function. these variables copies of 3 variables pass in main function. 3 variables going passed swap function, takes 2 integer addresses. variable address you're passing scoped within sort function. use pointers keep more organized.
int main() { int *num1, *num2, *num3; cout << "enter first number => "; cin >> *num1; cout << "enter second number => "; cin >> *num2; cout << "enter third number => "; cin >> *num3; cout << endl, cout << "before sorting numbers\n" << *num1 << " " << *num2 << " " << *num3 << endl; sort( num1, num2, num3 ); cout << "after sorting numbers\n" << *num1 << " " << *num2 << " " << *num3 << endl; return 0; } void swap ( int *a, int *b ) { int *temp = a; = b; b = temp; } void sort ( int *a, int *b, int *c ) { if (*a > *b) swap(a, b); if (*a > *c) swap(a, c); if (*b > *c) swap(b, c); } i didn't have chance compile this, later today see if works.
Comments
Post a Comment