HP Fortran Programmer Guide (766160-001, March 2014)
Example 22 Example 8-2 sqr_complex.c
#include <stdio.h>
/* simulate Fortran’s complex number */
typedef struct
{
float real;
float imag;
}COMPLEX;
/* returns the square of the complex argument */
COMPLEX sqr_complex(COMPLEX cmx_val)
{
COMPLEX result;
float a, b;
/* copy both parts of the complex number into locals */
a = cmx_val.real;
b = cmx_val.imag;
/* square the complex number and store the results into
* the return variable
*/
result.imag = 2 * (a * b);
a = a * a;
b = b * b;
result.real = a - b;
return result;
}
Below are the command lines to compile, link, and execute the program, followed by the output
from a sample run.
$ cc -Aa -c sqr_complex.c
$ f90 pass_complex.f90 sqr_complex.o
$ a.out
C will square this complex number: (2.5,3.5)
The squared result is: (-6.0,17.5)
Derived types
Although the syntax of Fortran's derived types differs from that of C's structures, both languages
have similar default packing and alignment rules. HP Fortran uses the same packing rules and
alignments when laying out derived-type objects in memory that HP C uses for structures.
Pointers
Although the Fortran pointer differs in some respects from the C pointer, a pointer passed by Fortran
to a C function looks and acts the same as it does in C. The only precaution is that, when the
pointer is to an array (which will almost always be the case), the two languages store and access
arrays differently; see “Arrays” (page 116).
Allocatable arrays may be passed from Fortran to C like any other array, with the precaution about
array differences between the two languages. Strings (an array of characters in C) are a different
matter; see “C strings” (page 118)for information about passing strings from Fortran to C.
Argument-passing conventions
The important difference between the argument-passing conventions of HP C and HP Fortran is
that Fortran passes arguments by reference — that is, it passes the address of the argument —
whereas C passes non-array and non-pointer arguments by value — that is, it passes a copy of
the argument. This difference affects calls not only to user-written routines in C but also to all HP-UX
system calls and subroutines, which are accessed as C functions.
HP Fortran provides two built-in functions, %VALand %REF, to override Fortran’s default
argument-passing conventions to conform to C. These functions are applied to the actual arguments
you want to pass, either in the argument list of the routine you are calling or with the $HP$ ALIAS
Argument-passing conventions 113