Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing by reference

Status
Not open for further replies.

Essendry

IS-IT--Management
Nov 13, 2002
4
0
0
GB
Can anyone help me with a query? I need to use the passing by reference mechanism of c++ to pass back the results of a function. I am new to C++ and am having diffuculty achieving this. Does anyone have a snippit of code and a brief explanation on how it works?
 
[tt]void swapInts( int& item1, int& item2 )
{
int temp = item1;
item1 = item2;
item2 = temp;
}
[/tt]

When you call that function as:

[tt]swapInts( x, y );[/tt]

since the parameters are passed by reference, any changes made to them in the function are made to the actual parameters passed in. In this case, the values of x and y will be swapped.

The easiest way to think about references is that they are simply alternate names for other variables. In the above example, when the function is called, item1 becomes another name for x and item2 becomes another name for y.
 
By reference.

Passing the address of the variable. Refering to the address of the variable in memory. since the address is passed we are manipulating the original. The asterisk will reference the address of the first item in an array (string, array list). The ampersand will reference the address of the item if it is of a singular nature.

char string [] = "string";
int x = 1;
char c = "c";

*string = the address of the first character in the
string -> "s". basically the address of the
string.

&string [3] = the address of the fourth character in the
string.

&x = the address of the x value.
&c = the address of the c value.

&string = not permissable since the string is stored in
more than one memory space. we are in effect
asking for the address of an address. not cool.

string = the adress of the string as a whole, which seems to differ programatically from the adress of the first character of the string. this will show up when you display the two in an edit box. this might also be written as (&string [0]).

create an edit box on a form and a string.

on the form show method write.

char *s = new char[10];
strcpy (s, "string");
Edit1->Text = *s;

change the right value (in this case *s) to &s, *s [3],
s, etc... some interesting things will become clear.

Please correct me if I am wrong. This is what I have come to understand. I would hope someone can shed more light on this and perhaps we all shall benefit. and please understand that the above is by far not complete.

Please refer to information on pointers and pointer arithmetic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top