G'day guys, ive been reading Brian Overlands C++ Without Fear for a few weeks now on and off when i get the time, and im getting a little confused with the following.
pg 146:
Pointers(he's discussing why pointers are used and his reasoning is:
"The problem here is that when an argument is passed to a funciton, the function gets a copy of the argument, but upon return that copy is thrown away" - his example is a void double_it(int n) with a variable reference from above inside it.
**
Think i figured it out while i was typing this out, but i want to ask a question based on his code so ill type it out here
**
his original pointer code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#include <iostream>
using namespace std;
void double_it(int *p);
int main(){
int a = 5, b = 6;
cout<<"Value of a before doubling is: " << a << endl;
cout<<"Value of b before doubling is: " << b << endl;
double_it(&a); // pass address of a.
double_it(&b); // pass address of b.
cout<<"value of a after doubling is: " << a << endl;
cout<<"Value of b after doubling is: " << b << endl;
return 0;
}
void double_it(int *p){
*p = *p * 2;
}
|
Ok thats the base code, now if instead of using a pointer to passt the values to Double_it, could i instead use a return value on double_it? Wouldnt that negate the need for pointers in this case?
I understand how pointers work(going to be playing with them today to get more familiar), infact this language has been quite easy so far, just a few questions the book doesnt answer :)
- Marak