How to Pass a Variable by Reference

How do I pass a variable by reference?

Arguments are passed by assignment. The rationale behind this is twofold:

  1. the parameter passed in is actually a reference to an object (but the reference is passed by value)
  2. some data types are mutable, but others aren't

So:

  • If you pass a mutable object into a method, the method gets a reference to that same object and you can mutate it to your heart's delight, but if you rebind the reference in the method, the outer scope will know nothing about it, and after you're done, the outer reference will still point at the original object.

  • If you pass an immutable object to a method, you still can't rebind the outer reference, and you can't even mutate the object.

To make it even more clear, let's have some examples.

List - a mutable type

Let's try to modify the list that was passed to a method:

def try_to_change_list_contents(the_list):
print('got', the_list)
the_list.append('four')
print('changed to', the_list)

outer_list = ['one', 'two', 'three']

print('before, outer_list =', outer_list)
try_to_change_list_contents(outer_list)
print('after, outer_list =', outer_list)

Output:

before, outer_list = ['one', 'two', 'three']
got ['one', 'two', 'three']
changed to ['one', 'two', 'three', 'four']
after, outer_list = ['one', 'two', 'three', 'four']

Since the parameter passed in is a reference to outer_list, not a copy of it, we can use the mutating list methods to change it and have the changes reflected in the outer scope.

Now let's see what happens when we try to change the reference that was passed in as a parameter:

def try_to_change_list_reference(the_list):
print('got', the_list)
the_list = ['and', 'we', 'can', 'not', 'lie']
print('set to', the_list)

outer_list = ['we', 'like', 'proper', 'English']

print('before, outer_list =', outer_list)
try_to_change_list_reference(outer_list)
print('after, outer_list =', outer_list)

Output:

before, outer_list = ['we', 'like', 'proper', 'English']
got ['we', 'like', 'proper', 'English']
set to ['and', 'we', 'can', 'not', 'lie']
after, outer_list = ['we', 'like', 'proper', 'English']

Since the the_list parameter was passed by value, assigning a new list to it had no effect that the code outside the method could see. The the_list was a copy of the outer_list reference, and we had the_list point to a new list, but there was no way to change where outer_list pointed.

String - an immutable type

It's immutable, so there's nothing we can do to change the contents of the string

Now, let's try to change the reference

def try_to_change_string_reference(the_string):
print('got', the_string)
the_string = 'In a kingdom by the sea'
print('set to', the_string)

outer_string = 'It was many and many a year ago'

print('before, outer_string =', outer_string)
try_to_change_string_reference(outer_string)
print('after, outer_string =', outer_string)

Output:

before, outer_string = It was many and many a year ago
got It was many and many a year ago
set to In a kingdom by the sea
after, outer_string = It was many and many a year ago

Again, since the the_string parameter was passed by value, assigning a new string to it had no effect that the code outside the method could see. The the_string was a copy of the outer_string reference, and we had the_string point to a new string, but there was no way to change where outer_string pointed.

I hope this clears things up a little.

EDIT: It's been noted that this doesn't answer the question that @David originally asked, "Is there something I can do to pass the variable by actual reference?". Let's work on that.

How do we get around this?

As @Andrea's answer shows, you could return the new value. This doesn't change the way things are passed in, but does let you get the information you want back out:

def return_a_whole_new_string(the_string):
new_string = something_to_do_with_the_old_string(the_string)
return new_string

# then you could call it like
my_string = return_a_whole_new_string(my_string)

If you really wanted to avoid using a return value, you could create a class to hold your value and pass it into the function or use an existing class, like a list:

def use_a_wrapper_to_simulate_pass_by_reference(stuff_to_change):
new_string = something_to_do_with_the_old_string(stuff_to_change[0])
stuff_to_change[0] = new_string

# then you could call it like
wrapper = [my_string]
use_a_wrapper_to_simulate_pass_by_reference(wrapper)

do_something_with(wrapper[0])

Although this seems a little cumbersome.

Pass variables by reference in JavaScript

There is no "pass by reference" available in JavaScript. You can pass an object (which is to say, you can pass-by-value a reference to an object) and then have a function modify the object contents:

function alterObject(obj) {
obj.foo = "goodbye";
}

var myObj = { foo: "hello world" };

alterObject(myObj);

alert(myObj.foo); // "goodbye" instead of "hello world"

You can iterate over the properties of an array with a numeric index and modify each cell of the array, if you want.

var arr = [1, 2, 3];

for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i] + 1;
}

It's important to note that "pass-by-reference" is a very specific term. It does not mean simply that it's possible to pass a reference to a modifiable object. Instead, it means that it's possible to pass a simple variable in such a way as to allow a function to modify that value in the calling context. So:

 function swap(a, b) {
var tmp = a;
a = b;
b = tmp; //assign tmp to b
}

var x = 1, y = 2;
swap(x, y);

alert("x is " + x + ", y is " + y); // "x is 1, y is 2"

In a language like C++, it's possible to do that because that language does (sort-of) have pass-by-reference.

edit — this recently (March 2015) blew up on Reddit again over a blog post similar to mine mentioned below, though in this case about Java. It occurred to me while reading the back-and-forth in the Reddit comments that a big part of the confusion stems from the unfortunate collision involving the word "reference". The terminology "pass by reference" and "pass by value" predates the concept of having "objects" to work with in programming languages. It's really not about objects at all; it's about function parameters, and specifically how function parameters are "connected" (or not) to the calling environment. In particular, note that in a true pass-by-reference language — one that does involve objects — one would still have the ability to modify object contents, and it would look pretty much exactly like it does in JavaScript. However, one would also be able to modify the object reference in the calling environment, and that's the key thing that you can't do in JavaScript. A pass-by-reference language would pass not the reference itself, but a reference to the reference.

edit — here is a blog post on the topic. (Note the comment to that post that explains that C++ doesn't really have pass-by-reference. That is true. What C++ does have, however, is the ability to create references to plain variables, either explicitly at the point of function invocation to create a pointer, or implicitly when calling functions whose argument type signature calls for that to be done. Those are the key things JavaScript doesn't support.)

How does 'pass variable by reference' work?

You're mixing up the declaration of a variable with its usage.

After:

type a = x;
type &c = a;

the situation is exactly the same as if you had written:

type c = x;
type &a = c;

In both cases there is one variable and it has two names, a and c.

Since C++11 there is one difference, decltype(a) will pick up the reference as part of the type

When you use a or c in an expression thereafter, it refers to that variable.

When you have void foo(type &p, type q) (changed names to avoid confusion), then if you call foo(a, b);, then the name p becomes another name for the argument a. There is one object with two names, a (visible to caller) and p (visible in the function).

This latter case is usually implemented by compilers in the same way that passing by pointer is implemented (but implementation details are not something you should take into account when forming a mental model of what something means).

C intro - How to pass a parameter by reference in function?

  1. It is perfectly valid. You can initialize and pass any number of pointer variables with their reference.

  2. This is also valid..when you pass the variable address, you should store it into a pointers

you have to do some changes in your code,
You can assign directly a/b and a*b pointer variables *c & *d
Then you have to read double number with %lf format argument.

#include <stdio.h>
#include <string.h>

void myFunction(double a, double b, double *c, double *d)
{
*c = a/b; //change
*d = a*b; //change
printf("%lf %lf",*c,*d);
return;
//printf statements
}



int main()
{
//first and second double hold the scanf inputs
double first;
double second;

//unsure here - to reference c and d as parameters in the function, do I simply declare unfilled double variables here?
double *c;
double *d;

printf("Enter your first number\n");
scanf("%lf", &first); //change
printf("Enter your second number\n");
scanf("%lf", &second); //change

//call the function, first and second by value, &c / &d by reference - correct?
myFunction(first, second, &c,&d);
}

How to pass a pointer variable as a reference parameter?

I want to pass a pointer by reference, but I'm not sure how to do that.

For this, consider the following snippet

#include <iostream>

void test(int*& t)
{
t = nullptr;
}

int main()
{
int* i = new int(4);

test(i);

if (i == nullptr)
std::cout << "I was passed by reference" << std::endl;
}

in which is is passed by reference to test, where it is set to nullptr and the program prints: I was passed by reference.

I think this example should make clear how to pass a pointer by reference to a function.

So in your case the function signiture must change to

void LinkedList::move_five_nodes(Node*& ptr1, Node*& ptr2) { ... }

Passing by reference in C

Because you're passing the value of the pointer to the method and then dereferencing it to get the integer that is pointed to.

Pass a Variable Reference In React?

JavaScript is always pass by value (though for objects, their values are their references). What I'd do in this case is set state based on passed keys. So, something like this (assuming the use of class properties):

class Example extends React.Component {
state = {
email: '',
password: '',
}

setInput = (key) => (event) => {
this.setState({ [key]: event.target.value });
}

render() {
return (
<div>
<input value={this.state.email} onChange={this.setInput('email')} />
<input value={this.state.password} onChange={this.setInput('password')} />
</div>
);
}
}

Here, setInput is a curried function. So, you can specify a certain key in state you want to change, then it returns a handler for that specific key using computed properties.

Pass Variables As Reference AS3

There are two types of data in AS3:

  1. Plain data: Boolean, String, Number, int, uint — always passed as values.
  2. Objects: Object, Array and literally everything else — always passed as a pointer/reference rather than through copy/clone.

There's no trick, like in C/C++ there is, to pass some plain variable as a pointer to let a method modify the original and only value.

That said, there are two ways around.

Solution №1: you can pass variables indirectly, in pairs like container → variable name.

function doIt(A:Object, a:String):void
{
A[a] = RNG(20);
}

Solution №2: devise a custom wrapper class to cross the border between plain and object data.

Implementation:

package
{
public class Oint
{
public var data:int;

// Class constructor.
public function Oint(value:int = 0)
{
data = value;
}

// There's always nice to have a interface methods,
// rather than member or getter/setter, because
// you can actually link to read/write methods.
public function read():int
{
return data;
}

public function write(value:int):void
{
data = value;
}

// With this you can use Oint variables in math expressions.
public function valueOf():Object
{
return data;
}

// With this you can trace Oint variables and see their values.
public function toString():String
{
return data.toString();
}
}
}

Usage:

function random(a:Oint, b:Oint, c:Oint):void
{
a.data = RNG(20);
b.data = RNG(25);
c.data = RNG(30);
}

Passing an integer by reference in Python

It doesn't quite work that way in Python. Python passes references to objects. Inside your function you have an object -- You're free to mutate that object (if possible). However, integers are immutable. One workaround is to pass the integer in a container which can be mutated:

def change(x):
x[0] = 3

x = [1]
change(x)
print x

This is ugly/clumsy at best, but you're not going to do any better in Python. The reason is because in Python, assignment (=) takes whatever object is the result of the right hand side and binds it to whatever is on the left hand side *(or passes it to the appropriate function).

Understanding this, we can see why there is no way to change the value of an immutable object inside a function -- you can't change any of its attributes because it's immutable, and you can't just assign the "variable" a new value because then you're actually creating a new object (which is distinct from the old one) and giving it the name that the old object had in the local namespace.

Usually the workaround is to simply return the object that you want:

def multiply_by_2(x):
return 2*x

x = 1
x = multiply_by_2(x)

*In the first example case above, 3 actually gets passed to x.__setitem__.



Related Topics



Leave a reply



Submit