eXistenz
asked on
About pointers & functions.
#include <iostream.h>
void exchange(int a, int b)
{
int c=a;
a=b;
b=c;
}
void main()
{
int x=10, y=20;
exchange(x,y);
cout << "x=" << x << "y=" << y ;
}
I am new at C++ and lately, I've learned the pointers. I understand them well, but I dunno when we use them. In the program above why doesn't it do value exchange ?
void exchange(int a, int b)
{
int c=a;
a=b;
b=c;
}
void main()
{
int x=10, y=20;
exchange(x,y);
cout << "x=" << x << "y=" << y ;
}
I am new at C++ and lately, I've learned the pointers. I understand them well, but I dunno when we use them. In the program above why doesn't it do value exchange ?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
yeah, my target from this snippet was to understand why I should use pointers here. thanks hongjun, bcladd . :) I understand now .
ASKER
Can you please explain when we have to use pointers ?
You must use pointers with _dynamically allocated memory_. That is, if you use new (or malloc) to allocate memory on the heap, that memory has no name. The only way to refer to it is by its location; a pointer holds the location of an object of the appropriate type in memory.
As parameters, you typically only need to use pointers when passing around dynamically allocated memory (or linked-lists or trees of dynamically allocated memory). When working with parameters you want to modify, you can usually get better (easier to read, easier to maintain, easier to use) results by using reference parameters.
-bcl
As parameters, you typically only need to use pointers when passing around dynamically allocated memory (or linked-lists or trees of dynamically allocated memory). When working with parameters you want to modify, you can usually get better (easier to read, easier to maintain, easier to use) results by using reference parameters.
-bcl
void exchange(int a, int b)
{
int c=a;
a=b;
b=c;
}
void main()
{
int x=10, y=20;
exchange(x,y);
cout << "x=" << x << "y=" << y ;
}
From your code, you are actually doing a pass by value into the exchange function. You are doing the exchanging of values in the function itself meaning to say if you do a display on variables a and b, you will see the exchange. However, once the function exits and returns to the main program, x and y still retain its original value. To do a "real" exchange, you can pass by using address like this
#include <iostream.h>
void exchange(int *a, int *b)
{
int c=*a;
*a=*b;
*b=c;
}
void main()
{
int x=10, y=20;
exchange(&x,&y);
cout << "x=" << x << "y=" << y ;
}
hongjun