1 Attachment(s)
Why couldn't I swap the values of two variables with *temp?
My teacher gave us a homework about exchanging the values of two variables with three different methods. These are callByValue, callByPointer and callByReference. I did all of them as you see the following code. However, I can't understand a point in the program. When I tried to use pointer temp in the function replace_CallByPointer, the compiler gave a warning. The warning was that:
Quote:
erlerini takaslama\main.cpp||In function 'void replace_CallByPointer(int*, int*)':|
erlerini takaslama\main.cpp|55|warning: 'temp' is used uninitialized in this function|
||=== Build finished: 0 errors, 1 warnings ===|
Thereupon, I put a value 0 to the pointer temp. So the compiler compiled without error and warning. But the program didn't run properly again.
I noticed that when I used variable temp instead of pointer temp, I can run the program properly. But why isn't the program working properly when I'm using pointer temp? I can't understand this point. Actually a variable temp is sufficient to accomplish the process, but yet it should run properly with pointer temp. Can anybody explain this case to me?
Code:
#include <iostream>
using namespace std;
void replace_CallByValue(int,int);
void replace_CallByPointer(int*,int*);
void replace_CallByReference(int&,int&);
int main()
{
int x,y;
cout << "Enter a value for x : ";
cin >> x;
cout << "Enter a value for y : ";
cin >> y;
cout << endl << endl << endl;
cout << "Values of x and y before the functions is no called." << endl;
cout << "x : " << x << endl << "y : " << y << endl << endl;
replace_CallByValue(x,y);
cout << "Values of x and y after the function 'callByValue'." << endl;
cout << "x : " << x << endl << "y : " << y << endl << endl;
replace_CallByPointer(&x,&y);
cout << "Values of x and y after the function 'callByPointer'." << endl;
cout << "x : " << x << endl << "y : " << y << endl << endl;
replace_CallByReference(x,y);
cout << "Values of x and y after the function 'callByReference'." << endl;
cout << "x : " << x << " y : " << y << endl;
}
void replace_CallByValue(int a,int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void replace_CallByPointer(int *c,int *d)
{
int *temp;
*temp = *c;
*c = *d;
*d = *temp;
}
//void replace_CallByPointer(int *c,int *d)
//{
// int temp;
//
//
// temp = *c;
// *c = *d;
// *d = temp;
//}
void replace_CallByReference(int &e,int &f)
{
int temp;
temp = e;
e = f;
f = temp;
}
Attachment 12014