Parameters
Parameter passing.
C++
Rust
Java
int multiply(int arg1, int &arg2)
{
int ret = arg1 * arg2;
arg1 = ret;
arg2 = ret;
return ret;
}
int main(unused int argc, unused char **argv)
{
int arg1 = 2;
int arg2 = 3;
int ret = multiply(arg1, arg2);
// prints 2 because it's passed by value
cout << "ARG1: " << arg1 << endl;
// prints 6 because it's passed by reference
cout << "ARG2: " << arg2 << endl;
// prints 6
cout << "RET: " << ret << endl;
return 0;
}
fn multiply(mut arg1: isize, arg2: &mut isize) -> (isize)
{
let ret = arg1 * *arg2;
arg1 = ret;
*arg2 = ret;
return ret;
}
fn main()
{
let arg1: isize = 2;
let mut arg2: isize = 3;
let ret = multiply(arg1, &mut arg2);
// prints 2 because it's passed by value
println!("ARG1: {}", arg1);
// prints 6 because it's passed by mutable reference
println!("ARG2: {}", arg2);
// prints 6
println!("RET: {}", ret);
}
public static int multiply(int arg1, int arg2)
{
int ret = arg1 * arg2;
arg1 = ret;
arg2 = ret;
return ret;
}
public static void main(String[] args)
{
int arg1 = 2;
int arg2 = 3;
int ret = multiply(arg1, arg2);
// prints 2 because it's passed by value
System.out.println("ARG1: " + arg1);
// prints 3 because it's passed by value
System.out.println("ARG2: " + arg2);
// prints 6
System.out.println("RET: " + ret);
All three languages default to pass-by-value if not otherwise specified.
C++ can specify a parameter as a reference, pointer, or pointer to a pointer. In this example, only pass-by-value and a reference is shown.
With Rust you must specify the mutability of a parameter even though it is passed by value and cannot change. For example,
if arg1
isn't marked as mut
, then the code will not compile as an attempt to change an immutable value is made.
Even though it is marked as mutable, the value doesn't change because it's pass-by-value. The second parameter must be
marked as both a reference (&
) and mutable (mut
) to be able to change it's value.
With Java there is no way to change the value of a primitive like int
. Integer
is also immutable
so it cannot be changed either. One "work-around" is to pass parameters via an array of size one. It is a reference to an
array that is passed by value into the function, so the contents of the array can be modified.