Comparison of passing function parameters: C++, Java, C#, Perl, PHP, JavaScript and Visual Basic

Parameters can be transferred between the main program and its functions/methods using either value parameters (by value) or reference parameters (by reference). With all the different languages that I used before, this topic comes out from time to time. So I think it would better for me to summarize them at one place:

C++
parameters can be passed either by value or by reference

  • pass parameters by value
    example: myfunction(myclass c)
  • pass by reference
    example: myfunction(myclass &c)

Java
pass parameters by value only.
One of the consequences of such constraint is that there is no easy way to implement the simple swap(x,y) function as in C++ or C#

see the comment here

C#
similar to C++, parameters can be passed either by value or by reference

  • pass parameters by value
    example: myfunction(int i)
  • pass by reference
    example: myfunction(ref int i) or myfunction(out int i).
    Difference: ref needs the variable initialized before being called, while out doesn’t, see the microsoft array example

One uniqueness of C# compared to Java and C++ is its variable type, which will affect its behavior in passing parameters:

  • similar to Java but different from C++, C# class is a reference type, so the variables of class object are accessed via their references
  • similar to C++ but absent in Java, C# struct is a value type, so struct instances are accessed directly, not by references

Perl
Pass by reference. The original variables in the main program are passed to subroutine in the special array @_. See comment here.

PHP 5
Similar to C++, parameters can be passed by value or reference.

example: myfunction(myclass &$c)

See the manual here.

JavaScript
similar to Java, parameters are passed by value only. See comment here.

Visual Basic
Similar to C++, parameters can be passed by value or reference.

example: Sub Myfunction1(ByVal v As Integer), Sub Myfunction2(ByRef v As Integer)

Oracle PL/SQL 
By default OUT and IN OUT parameters are passed by value and IN parameters are passed by reference, but NOCOPY keyword can be used to change the OUT and IN OUT parameters to be passed by reference. See reference here

Leave a Reply