For now think of it in terms of passing values to functions. There are
two ways to do this. Pass by value and pass by reference. Pass by
value takes the value of a variable and passes it to another variable
to be used within a function. Like this:
//prototype
int function(int)
int main()
{
//initalize
int var1 = 0;
//call function
var1 = function1(var1) ;
cout<< var1 //var1 will output 2
return 0;
}
int function1( int variable )
{
variable = 2;
return variable;
}
Pass by reference doesn't pass the value to a new variable, instead the
same variable(s) are used within the function, so that any changes that
happen to the variables within the function, affect the variables from
the main function
//prototype
void function(int&)
int main()
{
//initalize
int var1 = 0; //after function1 executes var1's value will change to
2
//call function
function1(var1) ;
cout<< var1 //var1 will output 2
return 0;
}
int function1( int& variable )
{
variable = 2;
return;
}
The '&' ampersand is used in conjunction with a variable to talk about
it's address in memory. That's all variables really are, aliases for
addresses in memory. So even though these two programs up above output
the same, their solutions are different. The first one (pass by value)
copies the value of the variable to a new variable to be used within
the function, so any change to the variable within the function will
not affect the origianl one. The second one (pass by reference) is not
creating a new variable but instead uses the one initalized in the main
function, so any change within the function directly changes that
variable. It's really the only way to return multiple values from a
main function.
It's not an easy concept to learn but it's vitally important when you
start learning about pointers.
Alan wrote in message
<1132447594.028 664.201200@f14g 2000cwb.googleg roups.com>...[color=blue]
>a typo I made: the last sentance of the second to last paragraph should
>say "It's really the only way to return multiple values from a
>function."
>[/color]
"Alan" <bethnar@gmail. com> wrote in message
news:1132447594 .028664.201200@ f14g2000cwb.goo glegroups.com.. .[color=blue]
>a typo I made: the last sentance of the second to last paragraph should
> say "It's really the only way to return multiple values from a
> function."[/color]
I would tend to disagree.
struct ReturnStruct
{
bool Worked;
int Value;
}
ReturnStruct MyFunction( int SomeVal )
{
ReturnStruct ReturnThis;
if ( SomeVal > 10 )
ReturnThis.Work ed = true;
else
ReturnThis.Work ed = false;
ReturnThis.Valu e = SomeVal * 10;
return ReturnThis;
}
Although I will admit that is awfually horrible looking code. But it is in
fact another way.
Considering this person is a beginner, I thought it better to display
the simplest manner in which the concept is used. While there are more
complicated manners, I don't know how deep his knowledge is in C++ or
programming in general.
Comment