|
//file: swap2.cpp //date: 2004.01.16 //author: AOU #include <iostream.h> #include <string.h> void swap(int &a, int &b); void swap(float &a, float &b); void swap(char a[], char b[]); void main(void) { { int a, b; a = 3; b = 4; cout << "Initially a, b = " << a << ' ' << b << endl; swap(a, b); cout << "After swap a, b = " << a << ' ' << b << endl << endl; } { float a, b; a = 3.5; b = 4.5; cout << "Initially a, b = " << a << ' ' << b << endl; swap(a, b); cout << "After swap a, b = " << a << ' ' << b << endl << endl; } { char a[20]="Pittsburg"; char b[20]="Hello"; cout << "Initially a, b = " << a << ' ' << b << endl; swap(a, b); cout << "After swap a, b = " << a << ' ' << b << endl << endl; } } void swap(char a[], char b[]) { cout << " Entering function\n"; cout << " a = " << a << endl; cout << " b = " << b << endl; int n1 = strlen(a); int n2 = strlen(b); int n = n1; if (n1 < n2) n = n2; char *temp; temp = new char[n+1]; cout << " n = " << n << endl; strcpy(temp, a); cout << " temp = " << temp << endl; strcpy(a, b); cout << " a = " << a << endl; strcpy(b, temp); cout << " b = " << b << endl; cout << " Getting out of function\n"; } void swap(float &a, float &b) { float temp; temp = a; a = b; b = temp; } void swap(int &a, int &b) { int temp; temp = a; a = b; b = temp; } /* Output: Initially a, b = 3 4 After swap a, b = 4 3 Initially a, b = 3.5 4.5 After swap a, b = 4.5 3.5 Initially a, b = Pittsburg Hello Entering function a = Pittsburg b = Hello n = 9 temp = Pittsburg a = Hello b = Pittsburg Getting out of function After swap a, b = Hello Pittsburg Press any key to continue */ |