开发者

pass by reference but reference to data and not to variable [closed]

开发者 https://www.devze.com 2022-12-26 14:08 出处:网络
Closed. This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the que开发者_C百科stion so it focuses on one problem only by e
Closed. This question needs to be more focused. It is not currently accepting answers.

Want to improve this question? Update the que开发者_C百科stion so it focuses on one problem only by editing this post.

Closed 5 years ago.

Improve this question

This is psesudo code. In what programming language this is possible ?

def lab(input)
  input = ['90']
end

x = ['80']
lab(x)

puts x #=> value of x has changed from ['80'] to ['90]

I have written this in ruby but in ruby I get the final x value of 80 because ruby is pass-by-reference. However what is passed is the reference to the data held by x and not pointer to x itself same is true in JavaScript. So I am wondering if there is any programming language where the following is true.


There are several languages that support pass-by-reference: it was implicit in most Fortran versions for longer than most other programming languages have existed (some versions used copies back and forth, but the end result had better be the same;-), it was specified by var in Pascal in the '70s (though the default, if you didn't say var, was by copy), etc, etc.

Most modern languages (Java, Python, Ruby, Javascript, Go, ...) uniformly pass (and assign) by object-reference (which is what you call "reference to data"), though some are more complex and let you specify more precisely what you want (e.g., C++, C#).


So in Ruby, you can't make x reference another object from within a method, but you can change the object itself, in your case what you want can be achieved using mutating methods (Array#replace could be handy in case of arrays, for example):

def lab input
  input.replace ['90']
end

x = ['80']
#=> ["80"]
lab x
#=> ["90"]
x
#=> ["90"]


This is another way to make it work in Ruby using bindings as reference:

def lab(input, bnd)
  eval "#{input} = 90", bnd
end

x = 80
lab("x", binding)

More information at: http://onestepback.org/index.cgi/Tech/Ruby/RubyBindings.rdoc


This is possible in a language with true pass-by-reference.

C#

public void lab(ref string[] input) {
  input = new string[] {"90"};
}

string[] x = {"80"};
lab(x);

PHP

function lab(&$input) {
  $input = array('90');
}

$x = array('80');
lab($x);

C++

void lab(string *&input) {
  input = new string[1];
  input[0] = "90";
}

string *x = new string[1];
x[0] = "80";
lab(x);

Perl

sub lab {
  $_[0] = ['90'];
}

$x = ['80'];
lab($x);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号