2 Copyright 1988-2022 Free Software Foundation, Inc.
3 This is part of the GCC manual.
4 For copying conditions, see the copyright.rst file.
6 .. index:: extensions, implemented
8 .. _extensions-implemented-in-gnu-fortran:
10 Extensions implemented in GNU Fortran
11 *************************************
13 GNU Fortran implements a number of extensions over standard Fortran.
14 This chapter contains information on their syntax and meaning. There
15 are currently two categories of GNU Fortran extensions, those that
16 provide functionality beyond that provided by any standard, and those
17 that are supported by GNU Fortran purely for backward compatibility
18 with legacy compilers. By default, :option:`-std=gnu` allows the
19 compiler to accept both types of extensions, but to warn about the use
20 of the latter. Specifying either :option:`-std=f95`,
21 :option:`-std=f2003`, :option:`-std=f2008`, or :option:`-std=f2018`
22 disables both types of extensions, and :option:`-std=legacy` allows
23 both without warning. The special compile flag :option:`-fdec` enables
24 additional compatibility extensions along with those enabled by
25 :option:`-std=legacy`.
31 .. index:: kind, old-style
33 .. _old-style-kind-specifications:
35 Old-style kind specifications
36 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
38 GNU Fortran allows old-style kind specifications in declarations. These
41 .. code-block:: fortran
45 where ``TYPESPEC`` is a basic type (``INTEGER``, ``REAL``,
46 etc.), and where ``size`` is a byte count corresponding to the
47 storage size of a valid kind for that type. (For ``COMPLEX``
48 variables, ``size`` is the total size of the real and imaginary
49 parts.) The statement then declares ``x``, ``y`` and ``z`` to
50 be of type ``TYPESPEC`` with the appropriate kind. This is
51 equivalent to the standard-conforming declaration
53 .. code-block:: fortran
57 where ``k`` is the kind parameter suitable for the intended precision. As
58 kind parameters are implementation-dependent, use the ``KIND``,
59 ``SELECTED_INT_KIND`` and ``SELECTED_REAL_KIND`` intrinsics to retrieve
60 the correct value, for instance ``REAL*8 x`` can be replaced by:
62 .. code-block:: fortran
64 INTEGER, PARAMETER :: dbl = KIND(1.0d0)
67 .. _old-style-variable-initialization:
69 Old-style variable initialization
70 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
72 GNU Fortran allows old-style initialization of variables of the
75 .. code-block:: fortran
80 The syntax for the initializers is as for the ``DATA`` statement, but
81 unlike in a ``DATA`` statement, an initializer only applies to the
82 variable immediately preceding the initialization. In other words,
83 something like ``INTEGER I,J/2,3/`` is not valid. This style of
84 initialization is only allowed in declarations without double colons
85 (``::``); the double colons were introduced in Fortran 90, which also
86 introduced a standard syntax for initializing variables in type
89 Examples of standard-conforming code equivalent to the above example
92 .. code-block:: fortran
95 INTEGER :: i = 1, j = 2
96 REAL :: x(2,2) = RESHAPE((/0.,0.,0.,1./),SHAPE(x))
100 DATA i/1/, j/2/, x/3*0.,1./
102 Note that variables which are explicitly initialized in declarations
103 or in ``DATA`` statements automatically acquire the ``SAVE``
108 .. _extensions-to-namelist:
110 Extensions to namelist
111 ^^^^^^^^^^^^^^^^^^^^^^
113 GNU Fortran fully supports the Fortran 95 standard for namelist I/O
114 including array qualifiers, substrings and fully qualified derived types.
115 The output from a namelist write is compatible with namelist read. The
116 output has all names in upper case and indentation to column 1 after the
117 namelist name. Two extensions are permitted:
119 Old-style use of :samp:`$` instead of :samp:`&`
124 X(:)%Y(2) = 1.0 2.0 3.0
128 It should be noted that the default terminator is :samp:`/` rather than
131 Querying of the namelist when inputting from stdin. After at least
132 one space, entering :samp:`?` sends to stdout the namelist name and the names of
133 the variables in the namelist:
145 Entering :samp:`=?` outputs the namelist to stdout, as if
146 ``WRITE(*,NML = mynml)`` had been called:
153 X(1)%Y= 0.000000 , 1.000000 , 0.000000 ,
154 X(2)%Y= 0.000000 , 2.000000 , 0.000000 ,
155 X(3)%Y= 0.000000 , 3.000000 , 0.000000 ,
158 To aid this dialog, when input is from stdin, errors send their
159 messages to stderr and execution continues, even if ``IOSTAT`` is set.
161 ``PRINT`` namelist is permitted. This causes an error if
162 :option:`-std=f95` is used.
164 .. code-block:: fortran
167 REAL, dimension (4) :: x = (/1.0, 2.0, 3.0, 4.0/)
170 END PROGRAM test_print
172 Expanded namelist reads are permitted. This causes an error if
173 :option:`-std=f95` is used. In the following example, the first element
174 of the array will be given the value 0.00 and the two succeeding
175 elements will be given the values 1.00 and 2.00.
177 .. code-block:: fortran
180 X(1,1) = 0.00 , 1.00 , 2.00
183 When writing a namelist, if no ``DELIM=`` is specified, by default a
184 double quote is used to delimit character strings. If -std=F95, F2003,
185 or F2008, etc, the delim status is set to 'none'. Defaulting to
186 quotes ensures that namelists with character strings can be subsequently
187 read back in accurately.
189 .. _x-format-descriptor-without-count-field:
191 X format descriptor without count field
192 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
194 To support legacy codes, GNU Fortran permits the count field of the
195 ``X`` edit descriptor in ``FORMAT`` statements to be omitted.
196 When omitted, the count is implicitly assumed to be one.
198 .. code-block:: fortran
201 10 FORMAT (I1, X, I1)
203 .. _commas-in-format-specifications:
205 Commas in FORMAT specifications
206 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
208 To support legacy codes, GNU Fortran allows the comma separator
209 to be omitted immediately before and after character string edit
210 descriptors in ``FORMAT`` statements. A comma with no following format
211 decriptor is permited if the :option:`-fdec-blank-format-item` is given on
212 the command line. This is considered non-conforming code and is
215 .. code-block:: fortran
218 10 FORMAT ('FOO='I1' BAR='I2)
222 .. _missing-period-in-format-specifications:
224 Missing period in FORMAT specifications
225 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
227 To support legacy codes, GNU Fortran allows missing periods in format
228 specifications if and only if :option:`-std=legacy` is given on the
229 command line. This is considered non-conforming code and is
232 .. code-block:: fortran
238 .. _default-widths-for-f,-g-and-i-format-descriptors:
240 Default widths for F, G and I format descriptors
241 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
243 To support legacy codes, GNU Fortran allows width to be omitted from format
244 specifications if and only if :option:`-fdec-format-defaults` is given on the
245 command line. Default widths will be used. This is considered non-conforming
246 code and is discouraged.
248 .. code-block:: fortran
252 WRITE(*,10) value1, value1, value2
253 10 FORMAT ('F, G, I')
255 .. index:: I/O item lists
262 To support legacy codes, GNU Fortran allows the input item list
263 of the ``READ`` statement, and the output item lists of the
264 ``WRITE`` and ``PRINT`` statements, to start with a comma.
266 .. index:: Q exponent-letter
271 GNU Fortran accepts real literal constants with an exponent-letter
272 of ``Q``, for example, ``1.23Q45``. The constant is interpreted
273 as a ``REAL(16)`` entity on targets that support this type. If
274 the target does not support ``REAL(16)`` but has a ``REAL(10)``
275 type, then the real-literal-constant will be interpreted as a
276 ``REAL(10)`` entity. In the absence of ``REAL(16)`` and
277 ``REAL(10)``, an error will occur.
279 .. index:: BOZ literal constants
281 .. _boz-literal-constants:
283 BOZ literal constants
284 ^^^^^^^^^^^^^^^^^^^^^
286 Besides decimal constants, Fortran also supports binary (``b``),
287 octal (``o``) and hexadecimal (``z``) integer constants. The
288 syntax is: :samp:`prefix quote digits quote`, where the prefix is
289 either ``b``, ``o`` or ``z``, quote is either ``'`` or
290 ``"`` and the digits are ``0`` or ``1`` for binary,
291 between ``0`` and ``7`` for octal, and between ``0`` and
292 ``F`` for hexadecimal. (Example: ``b'01011101'``.)
294 Up to Fortran 95, BOZ literal constants were only allowed to initialize
295 integer variables in DATA statements. Since Fortran 2003 BOZ literal
296 constants are also allowed as actual arguments to the ``REAL``,
297 ``DBLE``, ``INT`` and ``CMPLX`` intrinsic functions.
298 The BOZ literal constant is simply a string of bits, which is padded
299 or truncated as needed, during conversion to a numeric type. The
300 Fortran standard states that the treatment of the sign bit is processor
301 dependent. Gfortran interprets the sign bit as a user would expect.
303 As a deprecated extension, GNU Fortran allows hexadecimal BOZ literal
304 constants to be specified using the ``X`` prefix. That the BOZ literal
305 constant can also be specified by adding a suffix to the string, for
306 example, ``Z'ABC'`` and ``'ABC'X`` are equivalent. Additionally,
307 as extension, BOZ literals are permitted in some contexts outside of
308 ``DATA`` and the intrinsic functions listed in the Fortran standard.
309 Use :option:`-fallow-invalid-boz` to enable the extension.
311 .. index:: array, indices of type real
313 .. _real-array-indices:
318 As an extension, GNU Fortran allows the use of ``REAL`` expressions
319 or variables as array indices.
321 .. index:: operators, unary
328 As an extension, GNU Fortran allows unary plus and unary minus operators
329 to appear as the second operand of binary arithmetic operators without
330 the need for parenthesis.
332 .. code-block:: fortran
336 .. index:: conversion, to integer, conversion, to logical
338 .. _implicitly-convert-logical-and-integer-values:
340 Implicitly convert LOGICAL and INTEGER values
341 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
343 As an extension for backwards compatibility with other compilers, GNU
344 Fortran allows the implicit conversion of ``LOGICAL`` values to
345 ``INTEGER`` values and vice versa. When converting from a
346 ``LOGICAL`` to an ``INTEGER``, ``.FALSE.`` is interpreted as
347 zero, and ``.TRUE.`` is interpreted as one. When converting from
348 ``INTEGER`` to ``LOGICAL``, the value zero is interpreted as
349 ``.FALSE.`` and any nonzero value is interpreted as ``.TRUE.``.
351 .. code-block:: fortran
356 .. code-block:: fortran
361 However, there is no implicit conversion of ``INTEGER`` values in
362 ``if`` -statements, nor of ``LOGICAL`` or ``INTEGER`` values
365 .. index:: Hollerith constants
367 .. _hollerith-constants-support:
369 Hollerith constants support
370 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
372 GNU Fortran supports Hollerith constants in assignments, ``DATA``
373 statements, function and subroutine arguments. A Hollerith constant is
374 written as a string of characters preceded by an integer constant
375 indicating the character count, and the letter ``H`` or
376 ``h``, and stored in bytewise fashion in a numeric (``INTEGER``,
377 ``REAL``, or ``COMPLEX``), ``LOGICAL`` or ``CHARACTER`` variable.
378 The constant will be padded with spaces or truncated to fit the size of
379 the variable in which it is stored.
381 Examples of valid uses of Hollerith constants:
383 .. code-block:: fortran
386 data x /16Habcdefghijklmnop, 16Hqrstuvwxyz012345/
387 x(1) = 16HABCDEFGHIJKLMNOP
390 Examples of Hollerith constants:
392 .. code-block:: fortran
395 a = 0H ! Invalid, at least one character is needed.
397 a = 8H12345678 ! Valid, but the Hollerith constant will be truncated.
398 a = 3Hxyz ! Valid, but the Hollerith constant will be padded.
400 In general, Hollerith constants were used to provide a rudimentary
401 facility for handling character strings in early Fortran compilers,
402 prior to the introduction of ``CHARACTER`` variables in Fortran 77;
403 in those cases, the standard-compliant equivalent is to convert the
404 program to use proper character strings. On occasion, there may be a
405 case where the intent is specifically to initialize a numeric variable
406 with a given byte sequence. In these cases, the same result can be
407 obtained by using the ``TRANSFER`` statement, as in this example.
409 .. code-block:: fortran
412 a = transfer ("abcd", a) ! equivalent to: a = 4Habcd
414 The use of the :option:`-fdec` option extends support of Hollerith constants
417 .. code-block:: fortran
421 if (a .ne. 4habcd) then
422 write(*,*) "no match"
425 Supported types are numeric (``INTEGER``, ``REAL``, or ``COMPLEX``),
428 .. index:: conversion, to character
430 .. _character-conversion:
435 Allowing character literals to be used in a similar way to Hollerith constants
436 is a non-standard extension. This feature is enabled using
437 -fdec-char-conversions and only applies to character literals of ``kind=1``.
439 Character literals can be used in ``DATA`` statements and assignments with
440 numeric (``INTEGER``, ``REAL``, or ``COMPLEX``) or ``LOGICAL``
441 variables. Like Hollerith constants they are copied byte-wise fashion. The
442 constant will be padded with spaces or truncated to fit the size of the
443 variable in which it is stored.
447 .. code-block:: fortran
452 x = 'A' ! Will be padded.
453 x = 'ab1234' ! Will be truncated.
455 .. index:: pointer, Cray
462 Cray pointers are part of a non-standard extension that provides a
463 C-like pointer in Fortran. This is accomplished through a pair of
464 variables: an integer "pointer" that holds a memory address, and a
465 "pointee" that is used to dereference the pointer.
467 Pointer/pointee pairs are declared in statements of the form:
469 .. code-block:: fortran
471 pointer ( <pointer> , <pointee> )
475 .. code-block:: fortran
477 pointer ( <pointer1> , <pointee1> ), ( <pointer2> , <pointee2> ), ...
479 The pointer is an integer that is intended to hold a memory address.
480 The pointee may be an array or scalar.
481 If an assumed-size array is permitted within the scoping unit, a
482 pointee can be an assumed-size array.
483 That is, the last dimension may be left unspecified by using a ``*``
484 in place of a value. A pointee cannot be an assumed shape array.
485 No space is allocated for the pointee.
487 The pointee may have its type declared before or after the pointer
488 statement, and its array specification (if any) may be declared
489 before, during, or after the pointer statement. The pointer may be
490 declared as an integer prior to the pointer statement. However, some
491 machines have default integer sizes that are different than the size
492 of a pointer, and so the following code is not portable:
494 .. code-block:: fortran
499 If a pointer is declared with a kind that is too small, the compiler
500 will issue a warning; the resulting binary will probably not work
501 correctly, because the memory addresses stored in the pointers may be
502 truncated. It is safer to omit the first line of the above example;
503 if explicit declaration of ipt's type is omitted, then the compiler
504 will ensure that ipt is an integer variable large enough to hold a
507 Pointer arithmetic is valid with Cray pointers, but it is not the same
508 as C pointer arithmetic. Cray pointers are just ordinary integers, so
509 the user is responsible for determining how many bytes to add to a
510 pointer in order to increment it. Consider the following example:
512 .. code-block:: fortran
516 pointer (ipt, pointee)
520 The last statement does not set ``ipt`` to the address of
521 ``target(1)``, as it would in C pointer arithmetic. Adding ``1``
522 to ``ipt`` just adds one byte to the address stored in ``ipt``.
524 Any expression involving the pointee will be translated to use the
525 value stored in the pointer as the base address.
527 To get the address of elements, this extension provides an intrinsic
528 function ``LOC()``. The ``LOC()`` function is equivalent to the
529 ``&`` operator in C, except the address is cast to an integer type:
531 .. code-block:: fortran
534 pointer(ipt, arpte(10))
536 ipt = loc(ar) ! Makes arpte is an alias for ar
537 arpte(1) = 1.0 ! Sets ar(1) to 1.0
539 The pointer can also be set by a call to the ``MALLOC`` intrinsic
542 Cray pointees often are used to alias an existing variable. For
545 .. code-block:: fortran
552 As long as ``ipt`` remains unchanged, ``iarr`` is now an alias for
553 ``target``. The optimizer, however, will not detect this aliasing, so
554 it is unsafe to use ``iarr`` and ``target`` simultaneously. Using
555 a pointee in any way that violates the Fortran aliasing rules or
556 assumptions is illegal. It is the user's responsibility to avoid doing
557 this; the compiler works under the assumption that no such aliasing
560 Cray pointers will work correctly when there is no aliasing (i.e., when
561 they are used to access a dynamically allocated block of memory), and
562 also in any routine where a pointee is used, but any variable with which
563 it shares storage is not used. Code that violates these rules may not
564 run as the user intends. This is not a bug in the optimizer; any code
565 that violates the aliasing rules is illegal. (Note that this is not
566 unique to GNU Fortran; any Fortran compiler that supports Cray pointers
567 will 'incorrectly' optimize code with illegal aliasing.)
569 There are a number of restrictions on the attributes that can be applied
570 to Cray pointers and pointees. Pointees may not have the
571 ``ALLOCATABLE``, ``INTENT``, ``OPTIONAL``, ``DUMMY``,
572 ``TARGET``, ``INTRINSIC``, or ``POINTER`` attributes. Pointers
573 may not have the ``DIMENSION``, ``POINTER``, ``TARGET``,
574 ``ALLOCATABLE``, ``EXTERNAL``, or ``INTRINSIC`` attributes, nor
575 may they be function results. Pointees may not occur in more than one
576 pointer statement. A pointee cannot be a pointer. Pointees cannot occur
577 in equivalence, common, or data statements.
579 A Cray pointer may also point to a function or a subroutine. For
580 example, the following excerpt is valid:
582 .. code-block:: fortran
586 pointer (subptr,subpte)
595 A pointer may be modified during the course of a program, and this
596 will change the location to which the pointee refers. However, when
597 pointees are passed as arguments, they are treated as ordinary
598 variables in the invoked function. Subsequent changes to the pointer
599 will not change the base address of the array that was passed.
601 .. index:: CONVERT specifier
603 .. _convert-specifier:
608 GNU Fortran allows the conversion of unformatted data between little-
609 and big-endian representation to facilitate moving of data
610 between different systems. The conversion can be indicated with
611 the ``CONVERT`` specifier on the ``OPEN`` statement.
612 See :ref:`gfortran_convert_unit`, for an alternative way of specifying
613 the data format via an environment variable.
615 Valid values for ``CONVERT`` on most systems are:
617 * ``CONVERT='NATIVE'`` Use the native format. This is the default.
619 * ``CONVERT='SWAP'`` Swap between little- and big-endian.
621 * ``CONVERT='LITTLE_ENDIAN'`` Use the little-endian representation
622 for unformatted files.
624 * ``CONVERT='BIG_ENDIAN'`` Use the big-endian representation for
627 On POWER systems which support :option:`-mabi=ieeelongdouble`,
628 there are additional options, which can be combined with the others
629 with commas. Those are
631 * ``CONVERT='R16_IEEE'`` Use IEEE 128-bit format for
634 * ``CONVERT='R16_IBM'`` Use IBM ``long double`` format for
635 real ``REAL(KIND=16)``.
637 Using the option could look like this:
639 .. code-block:: fortran
641 open(file='big.dat',form='unformatted',access='sequential', &
642 convert='big_endian')
644 The value of the conversion can be queried by using
645 ``INQUIRE(CONVERT=ch)``. The values returned are
646 ``'BIG_ENDIAN'`` and ``'LITTLE_ENDIAN'``.
648 ``CONVERT`` works between big- and little-endian for
649 ``INTEGER`` values of all supported kinds and for ``REAL``
650 on IEEE systems of kinds 4 and 8. Conversion between different
651 'extended double' types on different architectures such as
652 m68k and x86_64, which GNU Fortran
653 supports as ``REAL(KIND=10)`` and ``REAL(KIND=16)``, will
656 *Note that the values specified via the GFORTRAN_CONVERT_UNIT
657 environment variable will override the CONVERT specifier in the
658 open statement*. This is to give control over data formats to
659 users who do not have the source code of their program available.
661 Using anything but the native representation for unformatted data
662 carries a significant speed overhead. If speed in this area matters
663 to you, it is best if you use this only for data that needs to be
673 OpenMP (Open Multi-Processing) is an application programming
674 interface (API) that supports multi-platform shared memory
675 multiprocessing programming in C/C++ and Fortran on many
676 architectures, including Unix and Microsoft Windows platforms.
677 It consists of a set of compiler directives, library routines,
678 and environment variables that influence run-time behavior.
680 GNU Fortran strives to be compatible to the
681 `OpenMP Application Program Interface v4.5 <https://openmp.org/specifications/>`_.
683 To enable the processing of the OpenMP directive ``!$omp`` in
684 free-form source code; the ``c$omp``, ``*$omp`` and ``!$omp``
685 directives in fixed form; the ``!$`` conditional compilation sentinels
686 in free form; and the ``c$``, ``*$`` and ``!$`` sentinels
687 in fixed form, :command:`gfortran` needs to be invoked with the
688 :option:`-fopenmp`. This also arranges for automatic linking of the
689 GNU Offloading and Multi Processing Runtime Library
692 The OpenMP Fortran runtime library routines are provided both in a
693 form of a Fortran 90 module named ``omp_lib`` and in a form of
694 a Fortran ``include`` file named :samp:`omp_lib.h`.
696 An example of a parallelized loop taken from Appendix A.1 of
697 the OpenMP Application Program Interface v2.5:
699 .. code-block:: fortran
701 SUBROUTINE A1(N, A, B)
704 !$OMP PARALLEL DO !I is private by default
706 B(I) = (A(I) + A(I-1)) / 2.0
708 !$OMP END PARALLEL DO
713 :option:`-fopenmp` implies :option:`-frecursive`, i.e., all local arrays
714 will be allocated on the stack. When porting existing code to OpenMP,
715 this may lead to surprising results, especially to segmentation faults
716 if the stacksize is limited.
720 On glibc-based systems, OpenMP enabled applications cannot be statically
721 linked due to limitations of the underlying pthreads-implementation. It
722 might be possible to get a working solution if
723 :command:`-Wl,--whole-archive -lpthread -Wl,--no-whole-archive` is added
724 to the command line. However, this is not supported by :command:`gcc` and
725 thus not recommended.
734 OpenACC is an application programming interface (API) that supports
735 offloading of code to accelerator devices. It consists of a set of
736 compiler directives, library routines, and environment variables that
737 influence run-time behavior.
739 GNU Fortran strives to be compatible to the
740 `OpenACC Application Programming
741 Interface v2.6 <https://www.openacc.org/>`_.
743 To enable the processing of the OpenACC directive ``!$acc`` in
744 free-form source code; the ``c$acc``, ``*$acc`` and ``!$acc``
745 directives in fixed form; the ``!$`` conditional compilation
746 sentinels in free form; and the ``c$``, ``*$`` and ``!$``
747 sentinels in fixed form, :command:`gfortran` needs to be invoked with
748 the :option:`-fopenacc`. This also arranges for automatic linking of
749 the GNU Offloading and Multi Processing Runtime Library
752 The OpenACC Fortran runtime library routines are provided both in a
753 form of a Fortran 90 module named ``openacc`` and in a form of a
754 Fortran ``include`` file named :samp:`openacc_lib.h`.
756 .. index:: argument list functions, %VAL, %REF, %LOC
758 .. _argument-list-functions:
760 Argument list functions %VAL, %REF and %LOC
761 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
763 GNU Fortran supports argument list functions ``%VAL``, ``%REF``
764 and ``%LOC`` statements, for backward compatibility with g77.
765 It is recommended that these should be used only for code that is
766 accessing facilities outside of GNU Fortran, such as operating system
767 or windowing facilities. It is best to constrain such uses to isolated
768 portions of a program--portions that deal specifically and exclusively
769 with low-level, system-dependent facilities. Such portions might well
770 provide a portable interface for use by the program as a whole, but are
771 themselves not portable, and should be thoroughly tested each time they
772 are rebuilt using a new compiler or version of a compiler.
774 ``%VAL`` passes a scalar argument by value, ``%REF`` passes it by
775 reference and ``%LOC`` passes its memory location. Since gfortran
776 already passes scalar arguments by reference, ``%REF`` is in effect
777 a do-nothing. ``%LOC`` has the same effect as a Fortran pointer.
779 An example of passing an argument by value to a C subroutine foo.:
781 .. code-block:: fortran
784 C prototype void foo_ (float x);
792 For details refer to the g77 manual
793 https://gcc.gnu.org/onlinedocs/gcc-3.4.6/g77/index.html#Top.
795 Also, ``c_by_val.f`` and its partner ``c_by_val.c`` of the
796 GNU Fortran testsuite are worth a look.
798 .. index:: EOF, BACKSPACE, REWIND
800 .. _read-write-after-eof-marker:
802 Read/Write after EOF marker
803 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
805 Some legacy codes rely on allowing ``READ`` or ``WRITE`` after the
806 EOF file marker in order to find the end of a file. GNU Fortran normally
807 rejects these codes with a run-time error message and suggests the user
808 consider ``BACKSPACE`` or ``REWIND`` to properly position
809 the file before the EOF marker. As an extension, the run-time error may
810 be disabled using -std=legacy.
812 .. index:: STRUCTURE, RECORD
814 .. _structure-and-record:
819 Record structures are a pre-Fortran-90 vendor extension to create
820 user-defined aggregate data types. Support for record structures in GNU
821 Fortran can be enabled with the :option:`-fdec-structure` compile flag.
822 If you have a choice, you should instead use Fortran 90's 'derived types',
823 which have a different syntax.
825 In many cases, record structures can easily be converted to derived types.
826 To convert, replace ``STRUCTURE /``:samp:`{structure-name}` ``/``
827 by ``TYPE`` :samp:`{type-name}`. Additionally, replace
828 ``RECORD /``:samp:`{structure-name}` ``/`` by
829 ``TYPE(``:samp:`{type-name}` ``)``. Finally, in the component access,
830 replace the period (``.``) by the percent sign (``%``).
832 Here is an example of code using the non portable record structure syntax:
834 .. code-block:: fortran
836 ! Declaring a structure named ``item'' and containing three fields:
837 ! an integer ID, an description string and a floating-point price.
840 CHARACTER(LEN=200) description
844 ! Define two variables, an single record of type ``item''
845 ! named ``pear'', and an array of items named ``store_catalog''
846 RECORD /item/ pear, store_catalog(100)
848 ! We can directly access the fields of both variables
850 pear.description = "juicy D'Anjou pear"
852 store_catalog(7).id = 7831
853 store_catalog(7).description = "milk bottle"
854 store_catalog(7).price = 1.2
856 ! We can also manipulate the whole structure
857 store_catalog(12) = pear
858 print *, store_catalog(12)
860 This code can easily be rewritten in the Fortran 90 syntax as following:
862 .. code-block:: fortran
864 ! ``STRUCTURE /name/ ... END STRUCTURE'' becomes
865 ! ``TYPE name ... END TYPE''
868 CHARACTER(LEN=200) description
872 ! ``RECORD /name/ variable'' becomes ``TYPE(name) variable''
873 TYPE(item) pear, store_catalog(100)
875 ! Instead of using a dot (.) to access fields of a record, the
876 ! standard syntax uses a percent sign (%)
878 pear%description = "juicy D'Anjou pear"
880 store_catalog(7)%id = 7831
881 store_catalog(7)%description = "milk bottle"
882 store_catalog(7)%price = 1.2
884 ! Assignments of a whole variable do not change
885 store_catalog(12) = pear
886 print *, store_catalog(12)
888 GNU Fortran implements STRUCTURES like derived types with the following
889 rules and exceptions:
891 * Structures act like derived types with the ``SEQUENCE`` attribute.
892 Otherwise they may contain no specifiers.
894 * Structures may contain a special field with the name ``%FILL``.
895 This will create an anonymous component which cannot be accessed but occupies
896 space just as if a component of the same type was declared in its place, useful
897 for alignment purposes. As an example, the following structure will consist
898 of at least sixteen bytes:
900 .. code-block:: fortran
908 * Structures may share names with other symbols. For example, the following
909 is invalid for derived types, but valid for structures:
911 .. code-block:: fortran
916 record /header/ header
918 * Structure types may be declared nested within another parent structure.
921 .. code-block:: fortran
923 structure /type-name/
925 structure [/<type-name>/] <field-list>
928 The type name may be ommitted, in which case the structure type itself is
929 anonymous, and other structures of the same type cannot be instantiated. The
930 following shows some examples:
932 .. code-block:: fortran
934 structure /appointment/
935 ! nested structure definition: app_time is an array of two 'time'
936 structure /time/ app_time (2)
937 integer(1) hour, minute
942 ! The 'time' structure is still usable
948 structure /appointment/
949 ! anonymous nested structure definition
951 integer(1) hour, minute
956 * Structures may contain ``UNION`` blocks. For more detail see the
957 section on :ref:`union-and-map`.
959 * Structures support old-style initialization of components, like
960 those described in :ref:`old-style-variable-initialization`. For array
961 initializers, an initializer may contain a repeat specification of the form
962 ``<literal-integer> * <constant-initializer>``. The value of the integer
963 indicates the number of times to repeat the constant initializer when expanding
964 the initializer list.
966 .. index:: UNION, MAP
973 Unions are an old vendor extension which were commonly used with the
974 non-standard :ref:`structure-and-record` extensions. Use of ``UNION`` and
975 ``MAP`` is automatically enabled with :option:`-fdec-structure`.
977 A ``UNION`` declaration occurs within a structure; within the definition of
978 each union is a number of ``MAP`` blocks. Each ``MAP`` shares storage
979 with its sibling maps (in the same union), and the size of the union is the
980 size of the largest map within it, just as with unions in C. The major
981 difference is that component references do not indicate which union or map the
982 component is in (the compiler gets to figure that out).
984 Here is a small example:
986 .. code-block:: fortran
991 character(2) w0, w1, w2
1000 ! After this assignment...
1003 ! The following is true:
1008 The two maps share memory, and the size of the union is ultimately six bytes:
1012 0 1 2 3 4 5 6 Byte offset
1013 -------------------------------
1015 -------------------------------
1018 \-------/ \-------/ \-------/
1021 \---------------------------/
1023 Following is an example mirroring the layout of an Intel x86_64 register:
1025 .. code-block:: fortran
1033 character(8) rh ! rah
1036 character(8) rl ! ral
1039 character(8) ex ! eax
1042 character(4) eh ! eah
1045 character(4) el ! eal
1062 ! After this assignment...
1063 a.rx = 'AAAAAAAA.BBB.C.D'
1065 ! The following is true:
1066 a.rx === 'AAAAAAAA.BBB.C.D'
1076 .. index:: intrinsics, integer
1078 .. _type-variants-for-integer-intrinsics:
1080 Type variants for integer intrinsics
1081 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1083 Similar to the D/C prefixes to real functions to specify the input/output
1084 types, GNU Fortran offers B/I/J/K prefixes to integer functions for
1085 compatibility with DEC programs. The types implied by each are:
1087 .. code-block:: fortran
1094 GNU Fortran supports these with the flag :option:`-fdec-intrinsic-ints`.
1095 Intrinsics for which prefixed versions are available and in what form are noted
1096 in :ref:`intrinsic-procedures`. The complete list of supported intrinsics is
1174 .. _automatic-and-static-attributes:
1176 AUTOMATIC and STATIC attributes
1177 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1179 With :option:`-fdec-static` GNU Fortran supports the DEC extended attributes
1180 ``STATIC`` and ``AUTOMATIC`` to provide explicit specification of entity
1181 storage. These follow the syntax of the Fortran standard ``SAVE`` attribute.
1183 ``STATIC`` is exactly equivalent to ``SAVE``, and specifies that
1184 an entity should be allocated in static memory. As an example, ``STATIC``
1185 local variables will retain their values across multiple calls to a function.
1187 Entities marked ``AUTOMATIC`` will be stack automatic whenever possible.
1188 ``AUTOMATIC`` is the default for local variables smaller than
1189 :option:`-fmax-stack-var-size`, unless :option:`-fno-automatic` is given. This
1190 attribute overrides :option:`-fno-automatic`, :option:`-fmax-stack-var-size`, and
1191 blanket ``SAVE`` statements.
1195 .. code-block:: fortran
1198 integer, automatic :: i ! automatic variable
1199 integer x, y ! static variables
1204 .. code-block:: fortran
1207 integer a, b, c, x, y, z
1211 ! a, b, c, and z are automatic
1212 ! x and y are static
1215 .. code-block:: fortran
1217 ! Compiled with -fno-automatic
1221 ! a is automatic; b, c, and d are static
1224 .. index:: intrinsics, math, intrinsics, trigonometric functions
1226 .. _extended-math-intrinsics:
1228 Extended math intrinsics
1229 ^^^^^^^^^^^^^^^^^^^^^^^^
1231 GNU Fortran supports an extended list of mathematical intrinsics with the
1232 compile flag :option:`-fdec-math` for compatability with legacy code.
1233 These intrinsics are described fully in :ref:`intrinsic-procedures` where it is
1234 noted that they are extensions and should be avoided whenever possible.
1236 Specifically, :option:`-fdec-math` enables the :ref:`COTAN` intrinsic, and
1237 trigonometric intrinsics which accept or produce values in degrees instead of
1238 radians. Here is a summary of the new intrinsics:
1263 \* Enabled with :option:`-fdec-math`.
1265 For advanced users, it may be important to know the implementation of these
1266 functions. They are simply wrappers around the standard radian functions, which
1267 have more accurate builtin versions. These functions convert their arguments
1268 (or results) to degrees (or radians) by taking the value modulus 360 (or 2\*pi)
1269 and then multiplying it by a constant radian-to-degree (or degree-to-radian)
1270 factor, as appropriate. The factor is computed at compile-time as 180/pi (or
1273 .. index:: form feed whitespace
1275 .. _form-feed-as-whitespace:
1277 Form feed as whitespace
1278 ^^^^^^^^^^^^^^^^^^^^^^^
1280 Historically, legacy compilers allowed insertion of form feed characters ('\f',
1281 ASCII 0xC) at the beginning of lines for formatted output to line printers,
1282 though the Fortran standard does not mention this. GNU Fortran supports the
1283 interpretation of form feed characters in source as whitespace for
1286 .. index:: type alias print
1288 .. _type-as-an-alias-for-print:
1290 TYPE as an alias for PRINT
1291 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1293 For compatibility, GNU Fortran will interpret ``TYPE`` statements as
1294 ``PRINT`` statements with the flag :option:`-fdec`. With this flag asserted,
1295 the following two examples are equivalent:
1297 .. code-block:: fortran
1299 TYPE *, 'hello world'
1301 .. code-block:: fortran
1303 PRINT *, 'hello world'
1307 .. _%loc-as-an-rvalue:
1312 Normally ``%LOC`` is allowed only in parameter lists. However the intrinsic
1313 function ``LOC`` does the same thing, and is usable as the right-hand-side of
1314 assignments. For compatibility, GNU Fortran supports the use of ``%LOC`` as
1315 an alias for the builtin ``LOC`` with :option:`-std=legacy`. With this
1316 feature enabled the following two examples are equivalent:
1318 .. code-block:: fortran
1324 .. code-block:: fortran
1329 .. index:: operators, xor
1336 GNU Fortran supports ``.XOR.`` as a logical operator with ``-std=legacy``
1337 for compatibility with legacy code. ``.XOR.`` is equivalent to
1338 ``.NEQV.``. That is, the output is true if and only if the inputs differ.
1340 .. index:: logical, bitwise
1342 .. _bitwise-logical-operators:
1344 Bitwise logical operators
1345 ^^^^^^^^^^^^^^^^^^^^^^^^^
1347 With :option:`-fdec`, GNU Fortran relaxes the type constraints on
1348 logical operators to allow integer operands, and performs the corresponding
1349 bitwise operation instead. This flag is for compatibility only, and should be
1350 avoided in new code. Consider:
1352 .. code-block:: fortran
1359 In this example, compiled with :option:`-fdec`, GNU Fortran will
1360 replace the ``.AND.`` operation with a call to the intrinsic
1361 function, yielding the bitwise-and of ``i`` and ``j``.
1363 Note that this conversion will occur if at least one operand is of integral
1364 type. As a result, a logical operand will be converted to an integer when the
1365 other operand is an integer in a logical operation. In this case,
1366 ``.TRUE.`` is converted to ``1`` and ``.FALSE.`` to ``0``.
1368 Here is the mapping of logical operator to bitwise intrinsic used with
1392 - complement of exclusive or
1394 .. _extended-i-o-specifiers:
1396 Extended I/O specifiers
1397 ^^^^^^^^^^^^^^^^^^^^^^^
1399 GNU Fortran supports the additional legacy I/O specifiers
1400 ``CARRIAGECONTROL``, ``READONLY``, and ``SHARE`` with the
1401 compile flag :option:`-fdec`, for compatibility.
1403 .. envvar:: CARRIAGECONTROL
1405 The ``CARRIAGECONTROL`` specifier allows a user to control line
1406 termination settings between output records for an I/O unit. The specifier has
1407 no meaning for readonly files. When ``CARRAIGECONTROL`` is specified upon
1408 opening a unit for formatted writing, the exact ``CARRIAGECONTROL`` setting
1409 determines what characters to write between output records. The syntax is:
1411 .. code-block:: fortran
1413 OPEN(..., CARRIAGECONTROL=cc)
1415 Where *cc* is a character expression that evaluates to one of the
1421 - One line feed between records (default)
1423 - Legacy interpretation of the first character (see below)
1425 - No separator between records
1427 With ``CARRIAGECONTROL='FORTRAN'``, when a record is written, the first
1428 character of the input record is not written, and instead determines the output
1429 record separator as follows:
1434 * - Leading character
1436 - Output separating character(s)
1440 - Carriage return only
1443 - Line feed and carriage return
1446 - Two line feeds and carriage return
1449 - Form feed and carriage return
1452 - Line feed (no carriage return)
1454 - Overprinting (no advance)
1457 .. envvar:: READONLY
1459 The ``READONLY`` specifier may be given upon opening a unit, and is
1460 equivalent to specifying ``ACTION='READ'``, except that the file may not be
1461 deleted on close (i.e. ``CLOSE`` with ``STATUS="DELETE"``). The syntax
1464 .. code-block:: fortran
1470 The ``SHARE`` specifier allows system-level locking on a unit upon opening
1471 it for controlled access from multiple processes/threads. The ``SHARE``
1472 specifier has several forms:
1474 .. code-block:: fortran
1480 Where *sh* in the first form is a character expression that evaluates to
1481 a value as seen in the table below. The latter two forms are aliases
1482 for particular values of *sh*:
1491 * - ``SHARE='DENYRW'``
1493 - Exclusive (write) lock
1494 * - ``SHARE='DENYNONE'``
1496 - Shared (read) lock
1498 In general only one process may hold an exclusive (write) lock for a given file
1499 at a time, whereas many processes may hold shared (read) locks for the same
1502 The behavior of locking may vary with your operating system. On POSIX systems,
1503 locking is implemented with ``fcntl``. Consult your corresponding operating
1504 system's manual pages for further details. Locking via ``SHARE=`` is not
1505 supported on other systems.
1507 .. index:: PARAMETER
1509 .. _legacy-parameter-statements:
1511 Legacy PARAMETER statements
1512 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
1514 For compatibility, GNU Fortran supports legacy PARAMETER statements without
1515 parentheses with :option:`-std=legacy`. A warning is emitted if used with
1516 :option:`-std=gnu`, and an error is acknowledged with a real Fortran standard
1517 flag (:option:`-std=f95`, etc...). These statements take the following form:
1519 .. code-block:: fortran
1522 parameter e = 2.718282
1528 .. _default-exponents:
1533 For compatibility, GNU Fortran supports a default exponent of zero in real
1534 constants with :option:`-fdec`. For example, ``9e`` would be
1535 interpreted as ``9e0``, rather than an error.