Share via


Passing By Value or By Reference

OverviewHow Do I

Each individual parameter can be passed by value or by reference (which places the address of the parameter on the stack). In Fortran, C, and C++, all addresses are the same size (4 bytes), so there is no passing by near or far reference. You need to make sure that for every call, the calling program and the called routine agree on how each parameter is passed. Otherwise, the called routine receives bad data.

The C/C++ technique for passing parameters is always the same, regardless of calling convention: All parameters are passed by value, except for arrays, which are translated into the address of the first member. To pass data by reference, pass a pointer to it.

The Fortran technique for passing parameters changes depending on the calling convention specified. By default, Fortran passes all data by reference (except the hidden length argument of strings, which is a special case). If the C or STDCALL attribute is used, the default changes to passing all data by value.

In Fortran, use the VALUE and REFERENCE attributes to specify pass by value or pass by reference. In mixed-language programming, it is a good idea to always specify passing technique explicitly rather than relying on defaults. For example, the following C declaration sets up a call to a Fortran subroutine:

extern void __stdcall TESTPROC( int ValParm, int *RefParm );

In the following example, the definition of TESTPROC in Fortran declares how each parameter is passed. The REFERENCE attribute is not strictly necessary in this example, but using it is a good idea, in case you later change the calling convention.

      SUBROUTINE TESTPROC( VALPARM, REFPARM )
      INTEGER*4 VALPARM [VALUE]
      INTEGER*4 REFPARM [REFERENCE]
      END

The following table summarizes parameter-passing defaults. Note that an array name in C is equated to its starting address. Therefore, arrays are passed by reference. To pass an array by value, declare a structure with the array as its only member.

C/C++ and Fortran Defaults for Passing Parameters

Language By value By reference
C/C++ variable *variable
Fortran variable[VALUE] variable[REFERENCE], or
variable
Fortran [C or STDCALL] variable[VALUE], or
variable
variable[REFERENCE]
C/C++ arrays struct {type}variable variable