by Dan East » Apr 17, 2001 @ 7:01am
Warren wrote:<br>int x = 3 <br>int y = x * 3 <br>y = 9 <br>x = 3 <br><br>Is that it? <br><br><br>Nope. As the other guys have said, this involves calling a function. A basic way of describing it is if a function is written to accept a parameter by reference, then that function can modify that variable's value. When passing by value the function cannot modify that variable's value (outside the scope of the function). I don't know if this will help you or confuse you more, but another technique that achieves the same result as passing by reference is to pass a pointer to the variable. Since the function has the pointer to the variable it can modify the variable's value:<br><br>Sample passing a pointer to a variable<br><br>void add(int *result, int a, int b) {<br>//Result is a pointer to an integer variable<br><br>*result=a+b;<br>}<br><br>int main() {<br><br>int result;<br><br>//We send "add" a pointer to "result" variable.<br>add(&result, 10, 20);<br><br>//The add function modified result<br>//so it is now equal to 30<br>}<br><br><br>Sample passing by reference<br><br>void add(int &result, int a, int b) {<br>result=a+b;<br>}<br><br>int main() {<br><br>int result;<br><br>add(result, 10, 20);<br><br>//The add function modified result<br>//so it is now equal to 30<br>}<br><br>Notice that passing by reference is simply a more elegant and less confusing method of passing pointers to variables. Most functions do not modify the variables that were passed to them, hence they aren't written to accept variables by reference. Note also that when you call the function you do not have to do anything different to pass by reference or pass by value.<br><br>Dan East