Intel Fortran Compiler Language Reference
Intel Fortran Compiler Language Reference
Copyright 2003 Intel Corporation Document Number: 253261-001 World Wide Web: http://developer.intel.com
Information in this document is provided in connection with Intel products. No license, express or implied, by estoppel or otherwise, to any intellectual property rights is granted by this document. EXCEPT AS PROVIDED IN INTEL'S TERMS AND CONDITIONS OF SALE FOR SUCH PRODUCTS, INTEL ASSUMES NO LIABILITY WHATSOEVER, AND INTEL DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY, RELATING TO SALE AND/OR USE OF INTEL PRODUCTS INCLUDING LIABILITY OR WARRANTIES RELATING TO FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR INFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT. Intel products are not intended for use in medical, life saving, or life sustaining applications. This Reference as well as the software described in it is furnished under license and may only be used or copied in accordance with the terms of the license. The information in this manual is furnished for informational use only, is subject to change without notice, and should not be construed as a commitment by Intel Corporation. Intel Corporation assumes no responsibility or liability for any errors or inaccuracies that may appear in this document or any software that may be provided in association with this document. Designers must not rely on the absence or characteristics of any features or instructions marked "reserved" or "undefined." Intel reserves these for future definition and shall have no responsibility whatsoever for conflicts or incompatibilities arising from future changes to them. The software described in this Reference may contain software defects which may cause the product to deviate from published specifications. Current characterized software defects are available on request. Intel SpeedStep, Intel Thread Checker, Celeron, Dialogic, i386, i486, iCOMP, Intel, Intel logo, Intel386, Intel486, Intel740, IntelDX2, IntelDX4, IntelSX2, Intel Inside, Intel Inside logo, Intel NetBurst, Intel NetStructure, Intel Xeon, Intel XScale, Itanium, MMX, MMX logo, Pentium, Pentium II Xeon, Pentium III Xeon, Pentium M, and VTune are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States and other countries. * Other names and brands may be claimed as the property of others. Copyright 2003 Intel Corporation. Portions Copyright 2001 Hewlett-Packard Development Company, L.P.
ii
Contents
About This Manual
Product Website and Support .................................................................. xxvi Related Publications................................................................................. xxvii Conventions ............................................................................................. xxix Platform Labels.................................................................................... xxxi
Chapter 1
Overview
Language Standards Conformance .......................................................... Language Compatibility............................................................................. Fortran 2003 Features............................................................................... Improved Features................................................................................ Fortran 95 Features................................................................................... New Features ....................................................................................... Improved Features................................................................................ Fortran 90 Features................................................................................... New Features ....................................................................................... Improved Features................................................................................ 1-2 1-2 1-2 1-3 1-3 1-3 1-4 1-5 1-5 1-7
Chapter 2
iii
Fixed and Tab Source Forms.............................................................. Fixed-Format Lines ........................................................................ Tab-Format Lines ........................................................................... Source Code Useable for All Source Forms .......................................
Chapter 3
iv
Contents
Data Types of Scalar Variables ........................................................... Specification of Data Type.............................................................. Implicit Typing Rules....................................................................... Arrays .................................................................................................. Whole Arrays .................................................................................. Array Elements ............................................................................... Array Sections ................................................................................ Array Constructors..........................................................................
Chapter 4
Chapter 5
Specification Statements
Type Declaration Statements..................................................................... 5-2 Declaration Statements for Noncharacter Types................................... 5-6 Declaration Statements for Character Types ........................................ 5-8 Declaration Statements for Derived Types.......................................... 5-10 Declaration Statements for Arrays ...................................................... 5-10 Explicit-Shape Specifications ......................................................... 5-11 Assumed-Shape Specifications ..................................................... 5-14 Assumed-Size Specifications......................................................... 5-15 Deferred-Shape Specifications ...................................................... 5-16 ALLOCATABLE Attribute and Statement ................................................. 5-17 AUTOMATIC and STATIC Attributes and Statements.............................. 5-18 COMMON Statement .............................................................................. 5-21 DATA Statement....................................................................................... 5-24 DIMENSION Attribute and Statement ..................................................... 5-27 EQUIVALENCE Statement ...................................................................... 5-29 Making Arrays Equivalent ................................................................... 5-31 Making Substrings Equivalent............................................................. 5-33 EQUIVALENCE and COMMON Interaction ........................................ 5-35 EXTERNAL Attribute and Statement....................................................... 5-38 IMPLICIT Statement ................................................................................ 5-39 INTENT Attribute and Statement............................................................. 5-41 INTRINSIC Attribute and Statement........................................................ 5-43 NAMELIST Statement ............................................................................. 5-45 OPTIONAL Attribute and Statement........................................................ 5-46 PARAMETER Attribute and Statement.................................................... 5-48 POINTER Attribute and Statement.......................................................... 5-50 PRIVATE and PUBLIC Attributes and Statements................................... 5-51 SAVE Attribute and Statement ................................................................ 5-54 TARGET Attribute and Statement............................................................ 5-55 VOLATILE Attribute and Statement ......................................................... 5-57
vi
Contents
Chapter 6
Dynamic Allocation
ALLOCATE Statement ............................................................................... Allocation of Allocatable Arrays............................................................. Allocation of Pointer Targets.................................................................. DEALLOCATE Statement .......................................................................... Deallocation of Allocatable Arrays......................................................... Deallocation of Pointer Targets ............................................................. NULLIFY Statement................................................................................... 6-2 6-3 6-4 6-5 6-6 6-7 6-8
Chapter 7
Execution Control
Branch Statements .................................................................................... 7-2 Unconditional GO TO Statement .......................................................... 7-2 Computed GO TO Statement................................................................ 7-3 The ASSIGN and Assigned GO TO Statements ................................... 7-4 ASSIGN Statement .......................................................................... 7-4 Assigned GO TO Statement............................................................. 7-5 Arithmetic IF Statement ........................................................................ 7-6 CALL Statement ........................................................................................ 7-7 CASE Constructs....................................................................................... 7-9 CONTINUE Statement............................................................................. 7-14 DO Constructs ......................................................................................... 7-14 Forms for DO Constructs .................................................................... 7-15 Execution of DO Constructs................................................................ 7-17 Iteration Loop Control..................................................................... 7-17 Nested DO Constructs ................................................................... 7-19 Extended Range............................................................................. 7-21 DO WHILE Statement ......................................................................... 7-23 CYCLE Statement............................................................................... 7-24 EXIT Statement................................................................................... 7-24 END Statement........................................................................................ 7-25 IF Construct and Statement..................................................................... 7-26 IF Construct ........................................................................................ 7-26 IF Statement........................................................................................ 7-31 PAUSE Statement.................................................................................... 7-32
vii
Chapter 8
viii
Contents
%LOC Function .............................................................................. Procedure Interfaces................................................................................ Determining When Procedures Require Explicit Interfaces ................ Defining Explicit Interfaces.................................................................. Defining Generic Names for Procedures ............................................ Defining Generic Operators ................................................................ Defining Generic Assignment ............................................................. CONTAINS Statement ............................................................................. ENTRY Statement ................................................................................... ENTRY Statements in Function Subprograms.................................... ENTRY Statements in Subroutine Subprograms ................................
8-44 8-45 8-46 8-46 8-49 8-50 8-51 8-53 8-53 8-55 8-56
Chapter 9
Intrinsic Procedures
Argument Keywords in Intrinsic Procedures .............................................. 9-3 Overview of Intrinsic Procedures ............................................................... 9-4 Categories of Intrinsic Functions........................................................... 9-4 Intrinsic Subroutines ........................................................................... 9-15 Bit Functions ....................................................................................... 9-16 Descriptions of Intrinsic Procedures ........................................................ 9-18 ABS ..................................................................................................... 9-18 ACHAR................................................................................................ 9-19 ACOS .................................................................................................. 9-20 ACOSD ............................................................................................... 9-20 ACOSH ............................................................................................... 9-21 ADJUSTL ............................................................................................ 9-21 ADJUSTR............................................................................................ 9-22 AIMAG................................................................................................. 9-22 AINT .................................................................................................... 9-23 ALL...................................................................................................... 9-23 ALLOCATED ....................................................................................... 9-24 ANINT ................................................................................................. 9-25 ANY..................................................................................................... 9-25 ASIN.................................................................................................... 9-26 ASIND ................................................................................................. 9-27
ix
ASINH ................................................................................................. ASSOCIATED ..................................................................................... ATAN ................................................................................................... ATAN2 ................................................................................................. ATAN2D............................................................................................... ATAND................................................................................................. ATANH................................................................................................. BADDRESS ........................................................................................ BIT_SIZE ............................................................................................ BTEST ................................................................................................ CACHESIZE (i64 only)........................................................................ CEILING ............................................................................................. CHAR.................................................................................................. CMPLX ............................................................................................... CONJG ............................................................................................... COS .................................................................................................... COSD ................................................................................................. COSH ................................................................................................. COTAN................................................................................................ COTAND ............................................................................................. COUNT ............................................................................................... CPU_TIME.......................................................................................... CSHIFT ............................................................................................... DATE................................................................................................... DATE_AND_TIME............................................................................... DBLE .................................................................................................. DCMPLX ............................................................................................. DFLOAT .............................................................................................. DIGITS ................................................................................................ DIM ..................................................................................................... DNUM ................................................................................................. DOT_PRODUCT................................................................................. DPROD ............................................................................................... DREAL................................................................................................
9-27 9-28 9-29 9-30 9-31 9-31 9-32 9-32 9-33 9-33 9-34 9-35 9-35 9-36 9-37 9-38 9-38 9-39 9-39 9-40 9-40 9-42 9-42 9-44 9-44 9-46 9-47 9-48 9-48 9-49 9-49 9-50 9-51 9-51
Contents
DSHIFTL ............................................................................................. DSHIFTR............................................................................................. EOF..................................................................................................... EOSHIFT............................................................................................. EPSILON............................................................................................. ERF ..................................................................................................... ERFC .................................................................................................. ERRSNS ............................................................................................. EXIT .................................................................................................... EXP ..................................................................................................... EXPONENT ........................................................................................ FLOOR................................................................................................ FP_CLASS.......................................................................................... FRACTION.......................................................................................... FREE................................................................................................... GETARG ............................................................................................. HUGE.................................................................................................. IACHAR............................................................................................... IAND.................................................................................................... IARGC................................................................................................. IARGPTR ............................................................................................ IBCHNG .............................................................................................. IBCLR.................................................................................................. IBITS ................................................................................................... IBSET.................................................................................................. ICHAR ................................................................................................. IDATE .................................................................................................. IEOR ................................................................................................... ILEN .................................................................................................... INDEX ................................................................................................. INT ...................................................................................................... INT_PTR_KIND................................................................................... INUM ................................................................................................... IOR......................................................................................................
9-52 9-52 9-53 9-54 9-56 9-57 9-57 9-58 9-59 9-59 9-60 9-60 9-61 9-61 9-62 9-62 9-64 9-64 9-65 9-66 9-66 9-67 9-67 9-68 9-69 9-70 9-71 9-71 9-72 9-73 9-73 9-75 9-76 9-76
xi
ISHA ................................................................................................... 9-77 ISHC ................................................................................................... 9-78 ISHFT ................................................................................................. 9-79 ISHFTC ............................................................................................... 9-80 ISHL.................................................................................................... 9-81 ISNAN ................................................................................................. 9-82 JNUM .................................................................................................. 9-82 KIND ................................................................................................... 9-82 LBOUND ............................................................................................. 9-83 LEADZ ................................................................................................ 9-84 LEN..................................................................................................... 9-85 LEN_TRIM .......................................................................................... 9-85 LGE..................................................................................................... 9-86 LGT..................................................................................................... 9-87 LLE ..................................................................................................... 9-87 LLT ...................................................................................................... 9-88 LOC .................................................................................................... 9-89 LOG .................................................................................................... 9-89 LOG10 ................................................................................................ 9-90 LOGICAL ............................................................................................ 9-91 MALLOC ............................................................................................. 9-91 MATMUL ............................................................................................. 9-92 MAX .................................................................................................... 9-93 MAXEXPONENT ................................................................................ 9-95 MAXLOC............................................................................................. 9-95 MAXVAL.............................................................................................. 9-97 MCLOCK ............................................................................................ 9-98 MERGE............................................................................................... 9-98 MIN ..................................................................................................... 9-99 MINEXPONENT ............................................................................... 9-100 MINLOC ............................................................................................ 9-100 MINVAL............................................................................................. 9-102 MM_PREFETCH .............................................................................. 9-103 MOD ................................................................................................. 9-105
xii
Contents
MODULO .......................................................................................... MULT_HIGH (i64 only) ..................................................................... MVBITS............................................................................................. NARGS ............................................................................................. NEAREST ......................................................................................... NINT.................................................................................................. NOT................................................................................................... NULL ................................................................................................. PACK................................................................................................. POPCNT ........................................................................................... POPPAR............................................................................................ PRECISION ...................................................................................... PRESENT ......................................................................................... PRODUCT ........................................................................................ QCMPLX ........................................................................................... QEXT ................................................................................................ QFLOAT ............................................................................................ QNUM ............................................................................................... QREAL .............................................................................................. RADIX ............................................................................................... RAN................................................................................................... RANDOM_NUMBER......................................................................... RANDOM_SEED .............................................................................. RANDU ............................................................................................. RANGE ............................................................................................. REAL................................................................................................. REPEAT ............................................................................................ RESHAPE ......................................................................................... RNUM ............................................................................................... RRSPACING ..................................................................................... SCALE .............................................................................................. SCAN ................................................................................................ SECNDS ........................................................................................... SELECTED_INT_KIND.....................................................................
9-106 9-106 9-107 9-108 9-110 9-110 9-111 9-112 9-113 9-114 9-114 9-114 9-115 9-116 9-117 9-117 9-118 9-119 9-119 9-120 9-120 9-121 9-122 9-124 9-124 9-125 9-126 9-127 9-128 9-128 9-128 9-129 9-130 9-130
xiii
SELECTED_REAL_KIND ................................................................. SET_EXPONENT ............................................................................. SHAPE.............................................................................................. SHIFTL ............................................................................................. SHIFTR ............................................................................................. SIGN ................................................................................................. SIN .................................................................................................... SIND ................................................................................................. SINH ................................................................................................. SIZE.................................................................................................. SIZEOF ............................................................................................. SPACING .......................................................................................... SPREAD ........................................................................................... SQRT ................................................................................................ SUM .................................................................................................. SYSTEM_CLOCK............................................................................. TAN ................................................................................................... TAND ................................................................................................ TANH ................................................................................................ TIME ................................................................................................. TINY.................................................................................................. TRAILZ ............................................................................................. TRANSFER ...................................................................................... TRANSPOSE.................................................................................... TRIM ................................................................................................. UBOUND .......................................................................................... UNPACK ........................................................................................... VERIFY ............................................................................................. ZEXT.................................................................................................
9-131 9-132 9-132 9-133 9-133 9-134 9-135 9-135 9-136 9-136 9-137 9-138 9-138 9-139 9-140 9-141 9-142 9-143 9-143 9-144 9-144 9-145 9-145 9-146 9-147 9-147 9-148 9-149 9-150
Chapter 10
xiv
Contents
Unit Specifier .................................................................................. 10-4 Format Specifier ............................................................................. 10-5 Namelist Specifier .......................................................................... 10-6 Record Specifier............................................................................. 10-6 I/O Status Specifier ........................................................................ 10-6 Branch Specifiers ........................................................................... 10-7 Advance Specifier .......................................................................... 10-8 Character Count Specifier .............................................................. 10-9 I/O Lists ............................................................................................... 10-9 Simple List Items in I/O Lists ........................................................ 10-10 implied-DO Lists in I/O Lists ......................................................... 10-12 READ Statements.................................................................................. 10-13 Forms for Sequential READ Statements........................................... 10-13 Rules for Formatted Sequential READ Statements...................... 10-15 Rules for List-Directed Sequential READ Statements.................. 10-15 Rules for Namelist Sequential READ Statements ........................ 10-18 Rules for Unformatted Sequential READ Statements .................. 10-23 Forms for Direct-Access READ Statements ..................................... 10-24 Rules for Formatted Direct-Access READ Statements ................ 10-25 Rules for Unformatted Direct-Access READ Statements ............. 10-26 Forms and Rules for Internal READ Statements .............................. 10-26 ACCEPT Statement ............................................................................... 10-28 WRITE Statements ................................................................................ 10-29 Forms for Sequential WRITE Statements ......................................... 10-29 Rules for Formatted Sequential WRITE Statements .................... 10-30 Rules for List-Directed Sequential WRITE Statements ................ 10-31 Rules for Namelist Sequential WRITE Statements ...................... 10-33 Rules for Unformatted Sequential WRITE Statements................. 10-34 Forms for Direct-Access WRITE Statements .................................... 10-35 Rules for Formatted Direct-Access WRITE Statements............... 10-36 Rules for Unformatted Direct-Access WRITE Statements ........... 10-36 Forms and Rules for Internal WRITE Statements............................. 10-36 PRINT and TYPE Statements ............................................................... 10-38 REWRITE Statement............................................................................. 10-39
xv
Chapter 11
I/O Formatting
Format Specifications .............................................................................. 11-2 Data Edit Descriptors............................................................................... 11-6 Forms for Data Edit Descriptors.......................................................... 11-6 General Rules for Numeric Editing ..................................................... 11-8 Integer Editing..................................................................................... 11-9 I Editing .......................................................................................... 11-9 B Editing....................................................................................... 11-11 O Editing ...................................................................................... 11-12 Z Editing ....................................................................................... 11-13 Real and Complex Editing ................................................................ 11-14 F Editing ....................................................................................... 11-15 E and D Editing ............................................................................ 11-16 EN Editing .................................................................................... 11-19 ES Editing .................................................................................... 11-20 G Editing ...................................................................................... 11-22 Complex Editing ........................................................................... 11-24 Logical Editing (L) ............................................................................. 11-25 Character Editing (A) ........................................................................ 11-26 Default Widths for Data Edit Descriptors .......................................... 11-28 Terminating Short Fields of Input Data ............................................. 11-29 Control Edit Descriptors......................................................................... 11-30 Forms for Control Edit Descriptors.................................................... 11-30 Positional Editing .............................................................................. 11-31 T Editing ....................................................................................... 11-31 TL Editing ..................................................................................... 11-32 TR Editing .................................................................................... 11-32 X Editing....................................................................................... 11-32 Sign Editing....................................................................................... 11-33 SP Editing .................................................................................... 11-33 SS Editing .................................................................................... 11-33 S Editing....................................................................................... 11-33 Blank Editing..................................................................................... 11-33 BN Editing .................................................................................... 11-34
xvi
Contents
BZ Editing..................................................................................... Scale Factor Editing (P) .................................................................... Slash Editing (/)................................................................................. Colon Editing (:) ................................................................................ Dollar Sign ($) and Backslash (\) Editing .......................................... Character Count Editing (Q).............................................................. Character String Edit Descriptors .......................................................... Character Constant Editing ............................................................... H Editing............................................................................................ Nested and Group Repeat Specifications.............................................. Variable Format Expressions ................................................................. Printing of Formatted Records............................................................... Interaction Between Format Specifications and I/O Lists ......................
11-34 11-34 11-36 11-37 11-37 11-38 11-38 11-39 11-39 11-40 11-41 11-42 11-43
Chapter 12
xvii
MODE Specifier ................................................................................ NAME Specifier ................................................................................ NAMED Specifier .............................................................................. NEXTREC Specifier.......................................................................... NUMBER Specifier ........................................................................... OPENED Specifier............................................................................ ORGANIZATION Specifier ................................................................ PAD Specifier .................................................................................... POSITION Specifier.......................................................................... READ Specifier ................................................................................. READWRITE Specifier ..................................................................... RECL Specifier ................................................................................. RECORDTYPE Specifier .................................................................. SEQUENTIAL Specifier .................................................................... SHARE Specifier (W*32, W*64) ....................................................... UNFORMATTED Specifier................................................................ WRITE Specifier ............................................................................... OPEN Statement ................................................................................... ACCESS Specifier ............................................................................ ACTION Specifier ............................................................................. ASSOCIATEVARIABLE Specifier ..................................................... BLANK Specifier ............................................................................... BLOCKSIZE Specifier....................................................................... BUFFERCOUNT Specifier................................................................ BUFFERED Specifier........................................................................ CARRIAGECONTROL Specifier....................................................... CONVERT Specifier ......................................................................... DEFAULTFILE Specifier.................................................................... DELIM Specifier ................................................................................ DISPOSE Specifier ........................................................................... FILE Specifier ................................................................................... FORM Specifier ................................................................................ IOFOCUS Specifier (W*32, W*64) ................................................... MAXREC Specifier ...........................................................................
12-14 12-14 12-14 12-15 12-15 12-15 12-16 12-16 12-16 12-17 12-17 12-17 12-18 12-18 12-19 12-19 12-19 12-20 12-24 12-25 12-25 12-26 12-26 12-26 12-27 12-28 12-28 12-30 12-30 12-31 12-32 12-32 12-33 12-33
xviii
Contents
MODE Specifier ................................................................................ NAME Specifier................................................................................. ORGANIZATION Specifier ................................................................ PAD Specifier .................................................................................... POSITION Specifier .......................................................................... READONLY Specifier........................................................................ RECL Specifier.................................................................................. RECORDSIZE Specifier.................................................................... RECORDTYPE Specifier .................................................................. SHARE Specifier (W*32, W*64)........................................................ SHARED Specifier ............................................................................ STATUS Specifier.............................................................................. TITLE Specifier (W*32, W*64) .......................................................... TYPE Specifier.................................................................................. USEROPEN Specifier ....................................................................... REWIND Statement............................................................................... UNLOCK Statement ..............................................................................
12-33 12-33 12-34 12-34 12-35 12-35 12-36 12-37 12-37 12-38 12-39 12-39 12-40 12-40 12-40 12-41 12-42
Chapter 13
Chapter 14
xix
ATTRIBUTES DECORATE........................................................... 14-12 ATTRIBUTES DEFAULT............................................................... 14-12 ATTRIBUTES DLLEXPORT and DLLIMPORT (W*32, W*64) ..... 14-13 ATTRIBUTES EXTERN................................................................ 14-13 ATTRIBUTES IGNORE_LOC....................................................... 14-13 ATTRIBUTES INLINE, NOINLINE, and FORCEDINLINE............ 14-14 ATTRIBUTES NO_ARG_CHECK ................................................ 14-14 ATTRIBUTES NOMIXED_STR_LEN_ARG ................................. 14-15 ATTRIBUTES REFERENCE and VALUE..................................... 14-15 ATTRIBUTES VARYING............................................................... 14-16 DECLARE and NODECLARE Directives.......................................... 14-16 DEFINE and UNDEFINE Directives.................................................. 14-17 DISTRIBUTE POINT Directive.......................................................... 14-18 FIXEDFORMLINESIZE Directive...................................................... 14-19 FREEFORM and NOFREEFORM Directives ................................... 14-20 IDENT Directive ................................................................................ 14-20 IF and IF DEFINED Directives .......................................................... 14-20 INTEGER Directive ........................................................................... 14-22 IVDEP Directive ................................................................................ 14-23 LOOP COUNT Directive ................................................................... 14-25 MESSAGE Directive ......................................................................... 14-26 OBJCOMMENT Directive ................................................................. 14-26 OPTIONS Directive........................................................................... 14-27 PACK Directive.................................................................................. 14-30 PARALLEL and NOPARALLEL Directives ........................................ 14-31 PREFETCH and NOPREFETCH Directives ..................................... 14-32 PSECT Directive ............................................................................... 14-33 REAL Directive.................................................................................. 14-35 STRICT and NOSTRICT Directives................................................. 14-36 SWP and NOSWP Directives (i64 only)............................................ 14-37 TITLE and SUBTITLE Directives ...................................................... 14-38 UNROLL and NOUNROLL Directives............................................... 14-39 VECTOR ALIGNED and VECTOR UNALIGNED Directives (i32 only) ....... 14-39
xx
Contents
VECTOR ALWAYS and NOVECTOR Directives (i32 only)................ VECTOR NONTEMPORAL Directive (i32 only)................................ OpenMP* Fortran Compiler Directives................................................... Data Scope Attribute Clauses ........................................................... COPYIN Clause ........................................................................... COPYPRIVATE Clause ................................................................ DEFAULT Clause.......................................................................... FIRSTPRIVATE Clause ................................................................ LASTPRIVATE Clause.................................................................. PRIVATE Clause........................................................................... REDUCTION Clause.................................................................... SHARED Clause .......................................................................... Conditional Compilation Rules .......................................................... Nesting and Binding Rules............................................................... ATOMIC Directive.............................................................................. BARRIER Directive ........................................................................... CRITICAL Directive........................................................................... DO Directive...................................................................................... FLUSH Directive ............................................................................... MASTER Directive ............................................................................ ORDERED Directive ......................................................................... PARALLEL Directive ......................................................................... PARALLEL DO Directive .................................................................. PARALLEL SECTIONS Directive ..................................................... SECTIONS Directive........................................................................ SINGLE Directive ............................................................................. THREADPRIVATE Directive.............................................................
14-40 14-41 14-42 14-44 14-44 14-44 14-45 14-46 14-46 14-46 14-47 14-49 14-49 14-50 14-52 14-53 14-54 14-55 14-59 14-60 14-61 14-62 14-64 14-66 14-67 14-68 14-69
Chapter 15
xxi
References to Nonestablished Names ............................................... 15-8 Association .............................................................................................. 15-9 Name Association............................................................................. 15-10 Argument Association .................................................................. 15-10 Use and Host Association ............................................................ 15-11 Pointer Association ........................................................................... 15-12 Storage Association .......................................................................... 15-13 Storage Units and Storage Sequence.......................................... 15-13 Array Association ......................................................................... 15-15
xxii
Contents
xxiii
I/O Statements........................................................................................... F-3 I/O Formatting............................................................................................ F-3 File Operation Statements......................................................................... F-4 Compiler Directives ................................................................................... F-5 Intrinsic Procedures................................................................................... F-7 Additional Language Features................................................................... F-9 Run-Time Library Routines...................................................................... F-10
Glossary Index
xxiv
xxv
Chapter 6, Dynamic Allocation, describes statements used in dynamic allocation. Chapter 7, Execution Control, describes constructs and statements that can transfer control within a program. Chapter 8, Program Units and Procedures, describes program units (including modules), subroutines and functions, and procedure interfaces. Chapter 9, Intrinsic Procedures, summarizes all intrinsic procedures. Chapter 10, Data Transfer I/O Statements,describes data transfer input/output (I/O) statements. Chapter 11, I/O Formatting, describes the rules for I/O formatting. Chapter 12, File Operation I/O Statements, describes auxiliary I/O statements you can use to perform file operations. Chapter 13, Compilation Control Statements, describes compilation control statements. Chapter 14, Directive Enhanced Compilation, describes general and parallel compiler directives. Chapter 15, Scope and Association, describes scope and association. Appendix A, Deleted and Obsolescent Language Features, describes deleted features in Fortran 95 and obsolescent language features in Fortran 95 and Fortran 90. Appendix B, Additional Language Features, describes some statements and language features supported for programs written in older versions of Fortran. Appendix C, The ASCII Character Set for Linux Systems, describes the ASCII character set available on Linux* systems. For information on character sets available on Windows* systems, see the online documentation for those systems. Appendix D, Data Representation Models, describes data representation models for numeric intrinsic functions. Appendix E, Run-Time Library Routines, summarizes the many run-time library routines. Appendix F, Summary of Language Extensions, summarizes Intel Fortran extensions to the Fortran 95 Standard. The Glossary contains abbreviated definitions of some commonly used terms in this manual.
xxvi
Intel also provides a support web site that contains a rich repository of self help information, including getting started tips, known product issues, product errata, license information, user forums, and more. Registering your product entitles you to one year of technical support and product updates through Intel Premier Support. Intel Premier Support is an interactive issue management and communication web site providing these services: Submit issues and review their status. Download product updates anytime of the day. To register your product, contact Intel, or seek product support, please visit: http://www.intel.com/software/products/support
Related Publications
The following is an alphabetical list of some commercially published documents that provide reference or tutorial information on Fortran 95 and Fortran 90: Compaq Visual Fortran by N. Lawrence; published by Digital Press* (Butterworth-Heinemann), ISBN: 1-55558-249-4. Digital Visual Fortran Programmers Guide by M. Etzel and K. Dickinson; published by Digital Press* (Butterworth-Heinemann), ISBN: 1-55558-218-4. Fortran 90 Explained by M. Metcalf and J. Reid; published by Oxford University Press, ISBN 0-19-853772-7. Fortran 90/95 Explained by M. Metcalf and J. Reid; published by Oxford University Press, ISBN 0-19-851888-9. Fortran 90/95 for Scientists and Engineers by S. Chapman; published by McGraw-Hill, ISBN 0-07-011938-4. Fortran 90 Handbook by J. Adams, W. Brainerd, J. Martin, B. Smith, and J. Wagener; published by Intertext Publications (McGraw-Hill), ISBN 0-07-000406-4. Fortran 90 Programming by T. Ellis, I. Philips, and T. Lahey; published by Addison-Wesley, ISBN 0201-54446-6. Introduction to Fortran 90/95 by Stephen J. Chapman; published by WCB McGraw-Hill, ISBN 0-07-011969-4. Programmers Guide to Fortran 90, Second Edition by W. Brainerd, C. Goldberg, and J. Adams; published by Unicomp, ISBN 0-07-000248-7. Intel does not endorse these books or recommend them over other books on the same subjects. The following copyrighted standard and specification documents contain precise descriptions of many of the features found in Intel Fortran:
xxvii
American National Standard Programming Language FORTRAN, ANSI X3.9-1978 American National Standard Programming Language Fortran 90, ANSI X3.198-1992 This Standard is equivalent to: International Standards Organization Programming Language Fortran, ISO/IEC 1539:1991 (E). American National Standard Programming Language Fortran 95, ANSI X3J3/96-007 This Standard is equivalent to: International Standards Organization Programming Language Fortran, ISO/IEC 1539-1:1997 (E). High Performance Fortran Language Specification, Version 1.1, Technical Report CRPC-TR-92225 OpenMP Fortran Application Program Interface, Version 1.1, November 1999 OpenMP Fortran Application Program Interface, Version 2.0, November 2000
Information about the target architecture is available from Intel and from most technical bookstores. Most Intel documents are available from the Intel Corporation web site at: http://www.intel.com Some helpful titles are: Intel Fortran Language Reference Intel Fortran Libraries Reference Intel Fortran Compiler Installing and Getting Started Intel Array Visualizer online help reference Intel Array Viewer online help reference Using the Intel License Manager for FLEXlm* Intel C++ Compiler User's Guide VTune Performance Analyzer online help Enhanced Debugger online help Intel Architecture Software Developer's Manual Vol. 1: Basic Architecture, Intel Corporation, doc. number 243190 Vol. 2: Instruction Set Reference Manual, Intel Corporation, doc. number 243191 Vol. 3: System Programming, Intel Corporation, doc. number 243192 Pentium Processor Family Developer's Manual Intel Processor Identification with the CPUID Instruction, Intel Corporation, doc. number 241618 Intel Itanium Architecture Manuals Intel Itanium Architecture Software Conventions & Runtime Architecture Guide Intel Itanium Assembler User's Guide Intel Itanium Architecture Assembly Language Reference Guide
xxviii
For more developer's manuals on Intel processors, refer to the Intel's Literature Center. The following sources might be useful in helping you understand basic optimization and vectorization terminology and technology: Intel Architecture Optimization Reference Manual Dependence Analysis, Utpal Banerjee (A Book Series on Loop Transformations for Restructuring Compilers). Kluwer Academic Publishers. 1997. The Structure of Computers and Computation: Volume I, David J. Kuck. John Wiley and Sons, New York, 1978. Loop Transformations for Restructuring Compilers: The Foundations, Utpal Banerjee (A Book Series on Loop Transformations for Restructuring Compilers). Kluwer Academic Publishers. 1993. Loop parallelization, Utpal Banerjee (A Book Series on Loop Transformations for Restructuring Compilers). Kluwer Academic Publishers. 1994. High Performance Compilers for Parallel Computers, Michael J. Wolfe. Addison-Wesley, Redwood City. 1996. Supercompilers for Parallel and Vector Computers, H. Zima. ACM Press, New York, 1990. An Auto-vectorizing Compiler for the Intel Architecture, Aart Bik, Paul Grey, Milind Girkar, and Xinmin Tian. Submitted for publication Efficient Exploitation of Parallelism on Pentium III and Pentium 4 Processor-Based Systems, Aart Bik, Milind Girkar, Paul Grey, and Xinmin Tian.
Conventions
The following table describes the typographic and terminology conventions used in this manual:
Typographic Conventions
Extensions to Fortran 95 This color indicates extensions to the Fortran 95 Standard. These extensions may or may not be implemented by other compilers that conform to the language standard. Uppercase letters indicate Fortran95/90 statements, data types, directives, and other syntax keywords. Examples of statement keywords are WRITE, INTEGER, DO, and OPEN. This italic type indicates an keyword arguments in syntax, new terms, emphasized text, or a book title. Most new terms are defined in the Glossary of the Language Reference. This courier type indicates a code example, a derived type name, or a pathname.
option, option
CALL CPU_TIME
xxix
CTRL
Small capital letters indicate the names of keys and key sequences, such as CTRL+C. A plus indicates a combination of keys. For example, CTRL+E means to hold down the CTRL key while pressing the E key. Braces and vertical bars indicate a choice of items. You can usually only choose one of the items in the braces. In syntax, single square brackets indicate items that are optional. In code examples, they are used to show arrays. A horizontal ellipsis (three dots in a row) following an item indicates that the item preceding the ellipsis can be repeated. In code examples, a horizontal ellipsis means that not all of the statements are shown. An asterisk at the end of a word or name indicates it is a third-party product trademark.
Adobe Acrobat*
Terminology Conventions
compiler option This term refers to Linux* options and Windows* options that can be used on the compiler command line. This format refers to an online reference page; the section number of the page is shown in parentheses. For example, a reference to cat(1) indicates that you can find the material on the cat command in Section 1 of the reference pages. To read online reference pages, use the man command. Your operating system documentation also includes reference page descriptions. This term refers to the name of the common compiler language supported by the Intel Visual Fortran Compiler for Windows* and Intel Fortran Compiler for Linux* products. For more information on these compilers, see http://developer.intel.com/software/products/. This term refers to language information that is common to ANSI FORTRAN 77, ANSI/ISO Fortran 95/90, and Intel Fortran. This term refers to language information that is common to ANSI/ISO Fortran 95 and ANSI/ISO Fortran 90. This term refers to language features of ANSI/ISO Fortran 95. This term refers to language features of ANSI/ISO Fortran 90. This term refers to all supported Microsoft* Windows operating systems. (See also Platform Labels.) This term refers to all supported Linux operating systems. (See also Platform Labels.) This term refers to the INTEGER(KIND=1), INTEGER(KIND=2), INTEGER (INTEGER(KIND=4)), and INTEGER(KIND=8) data types as a group.
cat(1)
Intel Fortran
Fortran Fortran 95/90 Fortran 95 Fortran 90 Windows systems Linux systems integer
xxx
real REAL
This term refers to the REAL (REAL(KIND=4)), DOUBLE PRECISION (REAL(KIND=8)), and REAL(KIND=16) data types as a group. This term refers to the default data type of objects declared to be REAL. REAL is equivalent to REAL(KIND=4), unless a compiler option specifies otherwise. This term refers to the COMPLEX (COMPLEX(KIND=4)), DOUBLE COMPLEX (COMPLEX(KIND=8)), and COMPLEX(KIND=16) data types as a group. This term refers to the LOGICAL(KIND=1), LOGICAL(KIND=2), LOGICAL (LOGICAL(KIND=4)), and LOGICAL(KIND=8) data types as a group. This symbol indicates a nonprinting tab character. This symbol indicates a nonprinting blank character.
complex
logical
<Tab>
The following example shows how this manual's typographic conventions are used to indicate the syntax of the PARAMETER statement: PARAMETER [(] c = expr [, c = expr]...[)] This syntax shows that when you use this statement, you must specify the following: The keyword PARAMETER. An optional left parenthesis. One or more c = expr items, where c is a named constant and expr is a value. If you want to specify more than one c = expr item, a comma must separate the items. The three dots following the syntax mean you can enter as many of these sequences (a comma, followed by c = expr) as you like. An optional terminating right parenthesis. If you used the optional left parenthesis, you must use the terminating right parenthesis. The colored brackets ([ ]) indicate that the parentheses are optional only as an extension to standard Fortran 95.
Platform Labels
A platform is a combination of operating system and central processing unit (CPU) that provides a distinct environment in which to use a product (in this case, a language). This manual contains information for the following language platforms:
Platform1 Language
Intel Fortran
Operating System
Linux
CPU
IA-32
xxxi
CPU
Intel Itanium IA-32 IA-32 IA-32 Intel Itanium
1. For the latest information on the current language platforms, see the online Release Notes.
Information in this manual applies to all supported platforms unless it is otherwise labeled for a specific platform (or platforms), as follows:
L*X L*X32 L*X64 W*32 W*64 i32 i64 Applies to Linux* on Intel IA-32 processors and Intel Itanium processors. Applies to Linux on Intel IA-32 processors. Applies to Linux on Intel Itanium processors. Applies to Microsoft Windows* 2000, Windows XP, and Windows NT* 4.0 on Intel IA-32 processors. Applies to Microsoft Windows XP operating systems on Intel Itanium processors. Applies to 32-bit operating systems on Intel IA-32 processors. Applies to 64-bit operating systems on Intel Itanium processors.
For example, the IOFOCUS specifier (for an OPEN statement) is labeled "(W*32, W*64)", so this specifier is valid only on Windows operating systems.
xxxii
Overview
Figure 1-1 Graphic Representation of Intel Fortran
This chapter discusses Intel Fortran standards conformance and language compatibility, and provides an overview of Fortran 95, Fortran 90, and proposed Fortran 2003 features.
Fortran 90
FORTRAN 77
Fortran 95
Fortran Extensions
Fortran 95 includes Fortran 90 and most features of FORTRAN 77. Fortran 90 is a superset that includes FORTRAN 77. Intel Fortran fully supports the Fortran 95, Fortran 90, and FORTRAN 77 Standards.
1-1
See Also
Appendix F, Summary of Language Extensions, for a summary of Intel Fortran language extensions
Language Compatibility
Intel Fortran is highly compatible with Compaq* Fortran and Compaq Fortran 77 on supported platforms, and it is substantially compatible with PDP-11* and VAX* FORTRAN 77.
See Also
Your users guide for specific details on language compatibility, compiler options, and program conversion considerations
1. 2.
This is the same as International Standards Organization standard ISO/IEC 1539-1:1997 (E). This is the same as International Standards Organization standard ISO/IEC 1539:1991 (E).
1-2
Overview
Improved Features
The following Fortran 2003 features improve previous Fortran features: Enhancement to derived-type components, function results, and dummy arguments Components of derived types can now be allocatable and function results and dummy arguments can now be allocatable. For more information, see Derived-Type Definition, Functions, and Array Arguments.
Fortran 95 Features
This section briefly describes the Fortran 95 language features that have been implemented in Intel Fortran. Some features are new, while others are improvements to previous Fortran features.
New Features
The following Fortran 95 features are new to Fortran: The FORALL statement and construct In Fortran 90, you could build array values element-by-element by using array constructors and the RESHAPE and SPREAD intrinsics. The Fortran 95 FORALL statement and construct offer an alternative method. FORALL allows array elements, array sections, character substrings, or pointer targets to be explicitly specified as a function of the element subscripts. A FORALL construct allows several array assignments to share the same element subscript control. FORALL is a generalization of WHERE. They both allow masked array assignment, but FORALL uses element subscripts, while WHERE uses the whole array. For more information, see FORALL Statement and Construct. PURE user-defined procedures Pure user-defined procedures do not have side effects, such as changing the value of a variable in a common block. To specify a pure procedure, use the PURE prefix in the function or subroutine statement. Pure functions are allowed in specification statements. For more information, see Pure Procedures. ELEMENTAL user-defined procedures An elemental user-defined procedure is a restricted form of pure procedure. An elemental procedure can be passed an array, which is acted upon one element at a time. To specify an elemental procedure, use the ELEMENTAL prefix in the function or subroutine statement. For more information, see Functions and Subroutines.
1-3
CPU_TIME intrinsic subroutine This new intrinsic subroutine returns a processor-dependent approximation of processor time. For more information, see CPU_TIME. NULL intrinsic function In Fortran 90, there was no way to assign a null value to the pointer by using a pointer assignment operation. A Fortran 90 pointer had to be explicitly allocated, nullified, or associated with a target during execution before association status could be determined. Fortran 95 provides the NULL intrinsic function that can be used to nullify a pointer. For more information, see NULL. New obsolescent features Fortran 95 deletes several language features that were obsolescent in Fortran 90, and identifies new obsolescent features. Intel Fortran fully supports features deleted in Fortran 95. For more information, see Appendix A, Deleted and Obsolescent Language Features.
Improved Features
The following Fortran 95 features improve previous Fortran features: Derived-type structure default initialization In derived-type definitions, you can now specify default initial values for derived-type components. For more information, see Default Initialization. Pointer initialization In Fortran 90, there was no way to define the initial value of a pointer. You can now specify default initialization for a pointer. For more information, see Derived-Type Definition and Default Initialization. Automatic deallocation of allocatable arrays Allocatable arrays whose status is allocated upon routine exit are now automatically deallocated. For more information, see Allocation of Allocatable Arrays. Enhanced CEILING and FLOOR intrinsic functions KIND can now be specified for these intrinsic functions. For more information, see CEILING and FLOOR. Enhanced MAXLOC and MINLOC intrinsic functions DIM can now be specified for these intrinsic functions. For more information, see MAXLOC and MINLOC.
1-4
Overview
Enhanced SIGN intrinsic function When a specific compiler option is specified, the SIGN function can now distinguish between positive and negative zero if the processor is capable of doing so. For more information, see SIGN. Printing of 0.0 When a specific compiler option is specified, a floating-point value of minus zero (0.0) can now be printed if the processor can represent it. Enhanced WHERE construct The WHERE construct has been improved to allow nested WHERE constructs and a masked ELSEWHERE statement. WHERE constructs can now be named. For more information, see WHERE Statement and Construct. Generic identifier allowed in END INTERFACE statement The END INTERFACE statement of an interface block defining a generic routine now can specify a generic identifier. For more information, see Defining Explicit Interfaces. Zero-length formats On output, when using I, B, O, Z, and F edit descriptors, the specified value of the field width can be zero. In such cases, the compiler selects the smallest possible positive actual field width that does not result in the field being filled with asterisks (*). Comments allowed in namelist input Fortran 95 allows comments (beginning with !) in namelist input data.
Fortran 90 Features
This section briefly describes the Fortran 90 language features that have been implemented in Intel Fortran. Some features are new, while others are improvements to previous Fortran features.
New Features
The following Fortran 90 features are new to Fortran: Free source form Fortran 90 provides a new free source form where line positions have no special meaning. There are no reserved columns, trailing comments can appear, and blanks have significance under certain circumstances (for example, P R O G R A M is not allowed as an alternative for PROGRAM). For more information, see Free Source Form.
1-5
Modules Fortran 90 provides a new form of program unit called a module, which is more powerful than (and overcomes limitations of) FORTRAN 77 block data program units. A module is a set of declarations that are grouped together under a single, global name. Modules let you encapsulate a set of related items such as data, procedures, and procedure interfaces, and make them available to another program unit. Module items can be made private to limit accessibility, provide data abstraction, and to create more secure and portable programs. For more information, see Modules and Module Procedures. User-defined (derived) data types and operators Fortran 90 lets you define new data types derived from any combination of the intrinsic data types and derived types. The derived-type object can be accessed as a whole, or its individual components can be accessed directly. You can extend the intrinsic operators (such as + and *) to user-defined data types, and also define new operators for operands of any type. For more information, see Derived Data Types and Defining Generic Operators. Array operations and features In Fortran 90, intrinsic operators and intrinsic functions can operate on array-valued operands (whole arrays or array sections). New features for arrays include whole, partial, and masked array assignment (including the WHERE statement for selective assignment), and array-valued constants and expressions. You can create user-defined array-valued functions, use array constructors to specify values of a one-dimensional array, and allocate arrays dynamically (using ALLOCATABLE and POINTER attributes). New intrinsic procedures create multidimensional arrays, manipulate arrays, perform operations on arrays, and support computations involving arrays (for example, SUM sums the elements of an array). For more information, see Arrays and Chapter 9, Intrinsic Procedures. Generic user-defined procedures In Fortran 90, user-defined procedures can be placed in generic interface blocks. This allows the procedures to be referenced using the generic name of the block. Selection of a specific procedure within the block is based on the properties of the argument, the same way as specific intrinsic functions are selected based on the properties of the argument when generic intrinsic function names are used. For more information, see Defining Generic Names for Procedures.
1-6
Overview
Pointers Fortran 90 pointers are mechanisms that allow dynamic access and processing of data. They allow arrays to be sized dynamically and they allow structures to be linked together. A pointer can be of any intrinsic or derived type. When a pointer is associated with a target, it can appear in most expressions and assignments. For more information, see POINTER Attribute and Statement and Pointer Assignments. Recursion Fortran 90 procedures can be recursive if the keyword RECURSIVE is specified on the FUNCTION or SUBROUTINE statement line. For more information, see Chapter 8, Program Units and Procedures. Interface blocks A Fortran 90 procedure can contain an interface block. Interface blocks can be used to do the following: Describe the characteristics of an external or dummy procedure Define a generic name for a procedure Define a new operator (or extend an intrinsic operator) Define a new form of assignment For more information, see Procedure Interfaces. Extensibility and redundancy By using user-defined data types, operators, and meanings, you can extend Fortran to suit your needs. These new data types and their operations can be packaged in modules, which can be used by one or more program units to provide data abstraction. With the addition of new features and capabilities, some old features become redundant and may eventually be removed from the language. For example, the functionality of the ASSIGN and assigned GO TO statements can be replaced more effectively by internal procedures. The use of certain old features of Fortran can result in less than optimal performance on newer hardware architectures. For more information, see your users guide. For a list of obsolescent features, see Appendix A, Deleted and Obsolescent Language Features.
Improved Features
The following Fortran 90 features improve previous Fortran features:
1-7
Additional features for source text Lowercase characters are now allowed in source text. A semicolon can be used to separate multiple statements on a single source line. Additional characters have been added to the Fortran character set, and names can have up to 31 characters (including underscores). For more information, see Chapter 2, Program Structure, Characters, and Source Forms. Improved facilities for numerical computation Intrinsic data types can be specified in a portable way by using a kind type parameter indicating the precision or accuracy required. There are also new intrinsic functions that allow you to specify numeric precision and inquire about precision characteristics available on a processor. For more information, see Chapter 3, Data Types, Constants, and Variables and Chapter 9, Intrinsic Procedures. Additional input/output features Fortran 90 provides additional keywords for the OPEN and INQUIRE statements. It also permits namelist formatting, and nonadvancing (stream) character-oriented input and output. For more information on formatting, see Chapter 10, Data Transfer I/O Statements; on OPEN and INQUIRE, see Chapter 12, File Operation I/O Statements. Additional control constructs Fortran 90 provides a new control construct (CASE) and improves the DO construct. The DO construct can now use CYCLE and EXIT statements, and can have additional (or no) control clauses (for example, WHILE). All control constructs (CASE, DO, and IF) can now be named. For more information, see Chapter 7, Execution Control. Additional intrinsic procedures Fortran 90 provides many more intrinsic procedures than existed in FORTRAN 77. Many of these new intrinsics support mathematical operations on arrays, including the construction and transformation of arrays. New bit manipulation and numerical accuracy intrinsics have been added. For more information, see Chapter 9, Intrinsic Procedures. Additional specification statements The following specification statements are new in Fortran 90: The INTENT statement (INTENT Attribute and Statement) The OPTIONAL statement (OPTIONAL Attribute and Statement) The Fortran 90 POINTER statement (POINTER Attribute and Statement) The PUBLIC and PRIVATE statements (PRIVATE and PUBLIC Attributes and Statements)
1-8
Overview
Additional way to specify attributes Fortran 90 lets you specify attributes (such as PARAMETER, SAVE, and INTRINSIC) in type declaration statements, as well as in specification statements. For more information, see Type Declaration Statements. Scope and Association These concepts were implicit in FORTRAN 77, but they are explicitly defined in Fortran 90. In FORTRAN 77, the term scoping unit applies to a program unit, but Fortran 90 expands the term to include internal procedures, interface blocks, and derived-type definitions. For more information, see Chapter 15, Scope and Association.
1-9
1-10
This chapter contains information on the following topics: An overview of program structure, including general information on statements and names (see Program Structure) Character Sets Source Forms
Program Structure
A Fortran program consists of one or more program units. A program unit is usually a sequence of statements that define the data environment and the steps necessary to perform calculations; it is terminated by an END statement. A program unit can be either a main program, an external subprogram, a module, or a block data program unit. An executable program contains one main program, and, optionally, any number of the other kinds of program units. Program units can be separately compiled. An external subprogram is a function or subroutine that is not contained within a main program, a module, or another subprogram. It defines a procedure to be performed and can be invoked from other program units of the Fortran program. Modules and block data program units are not executable, so they are not considered to be procedures. (Modules can contain module procedures, though, which are executable.) Modules contain definitions that can be made accessible to other program units: data and type definitions, definitions of procedures (called module subprograms), and procedure interfaces. Module subprograms can be either functions or subroutines. They can be invoked by other module subprograms in the module, or by other program units that access the module. A block data program unit specifies initial values for data objects in named common blocks. In Fortran 95/90, this type of program unit can be replaced by a module program unit.
2-1
Main programs, external subprograms, and module subprograms can contain internal subprograms. The entity that contains the internal subprogram is its host. Internal subprograms can be invoked only by their host or by other internal subprograms in the same host. Internal subprograms must not contain internal subprograms.
See Also
Chapter 8, Program Units and Procedures, for details on program units and procedures
Statements
Program statements are grouped into two general classes: executable and nonexecutable. An executable statement specifies an action to be performed. A nonexecutable statement describes program attributes, such as the arrangement and characteristics of data, as well as editing and data-conversion information.
2-2
Figure 2-1
OPTIONS Statements PROGRAM, FUNCTION. SUBROUTINE, MODULE, or BLOCK DATA Statement USE Statements IMPLICIT NONE Statements Comment Lines, INCLUDE Statements, and Directives PARAMETER Statements NAMELIST, FORMAT, and ENTRY Statements IMPLICIT Statements DerivedType Definitions, Interface Blocks, Type Declaration Statements, Statement Function Statements, and Specification Statements Executable Statements
DATA Statements
Note that in this figure, INCLUDE statements, directives, OPTIONS statements, and the order of NAMELIST statements are language extensions. PUBLIC and PRIVATE statements are only allowed in the scoping units of modules. In Fortran 95/90, NAMELIST statements can appear only among specification statements. However, Intel Fortran allows them to also appear among executable statements.
2-3
Table 2-1 shows other statements restricted from different types of scoping units.
Table 2-1 Statements Restricted in Scoping Units Scoping Unit
Main program Module
1
Restricted Statements
ENTRY and RETURN statements ENTRY, FORMAT, OPTIONAL, and INTENT statements, statement functions, and executable statements CONTAINS, ENTRY, and FORMAT statements, interface blocks, statement functions, and executable statements CONTAINS and ENTRY statements CONTAINS, DATA, ENTRY, SAVE, and FORMAT statements, statement functions, and executable statements
1. The scoping unit of a module does not include any module subprograms that the module contains.
See Also
Scope for details on scoping units
Names
Names identify entities within a Fortran program unit (such as variables, function results, common blocks, named constants, procedures, program units, namelist groups, and dummy arguments). In FORTRAN 77, names were called "symbolic names". A name can contain letters, digits, underscores ( _ ), and the dollar sign ($) special character. The first character must be a letter or a dollar sign. In Fortran 95/90, a name can contain up to 31 characters. Intel Fortran allows names up to 63 characters. The length of a module name (in MODULE and USE statements) may be restricted by your file system. NOTE. Be careful when defining names that contain dollar signs. On Linux* and Windows* systems, a dollar sign can be a symbol for command or symbol substitution in various shell and utility commands.
In an executable program, the names of the following entities are global and must be unique in the entire program:
2-4
Examples
The following examples show valid and invalid names:
Valid
NUMBER FIND_IT X
Invalid
5Q B.4 _WRONG
Explanation
Begins with a numeral. Contains a special character other than _ or $. Begins with an underscore.
See Also
Scope for details on the scope of names
Character Sets
Intel Fortran supports the following characters: The Fortran 95/90 character set which consists of the following: All uppercase and lowercase letters (A through Z and a through z) The numerals 0 through 9 The underscore ( _ ) The following special characters:
Character
or <Tab> = + *
Name
Blank (space) or tab Equal sign Plus sign Minus sign Asterisk
Character
: ! " % &
Name
Colon Exclamation point Quotation mark Percent sign Ampersand
2-5
2
/ ( ) , .
Character
Name
Slash Left parenthesis Right parenthesis Comma Period (decimal point) Apostrophe
Character
; < > ? $
Name
Semicolon Less than Greater than Question mark Dollar sign (currency symbol)
Other printable characters Printable characters include the tab character (09 hex) and ASCII characters with codes in the range 20(hex) through 7E(hex). Printable characters that are not in the Fortran 95/90 character set can only appear in comments, character constants, Hollerith constants, character string edit descriptors, and input/output records.
Uppercase and lowercase letters are treated as equivalent when used to specify program behavior (except in character constants and Hollerith constants).
See Also Appendix C, The ASCII Character Set for Linux Systems, for details on the ASCII character set for Linux systems The online documentation for Windows* systems for details on other character sets available for those systems
Source Forms
Within a program, source code can be in free, fixed, or tab form. Fixed or tab forms must not be mixed with free form in the same source program, but different source forms can be used in different source programs. All source forms allow lowercase characters to be used as an alternative to uppercase characters. Several characters are indicators in source code (unless they appear within a comment or a Hollerith or character constant). The following are rules for indicators in all source forms:
2-6
Comment indicator A comment indicator can precede the first statement of a program unit and appear anywhere within a program unit. If the comment indicator appears within a source line, the comment extends to the end of the line. An all blank line is also a comment line. Comments have no effect on the interpretation of the program unit. For more information on comment indicators in free source form, see Free Source Form; in fixed and tab source forms, see Fixed and Tab Source Forms. Statement separator More than one statement (or partial statement) can appear on a single source line if a statement separator is placed between the statements. The statement separator is a semicolon character (;). Consecutive semicolons (with or without intervening blanks) are considered to be one semicolon. If a semicolon is the last character on a line, or the last character before a comment, it is ignored. Continuation indicator A statement can be continued for more than one line by placing a continuation indicator on the line. Intel Fortran allows up to 511 continuation lines in a source program. Comments can occur within a continued statement, but comment lines cannot be continued. Within a program unit, the END statement cannot be continued, and no other statement in the program unit can have an initial line that appears to be the program unit END statement. For more information on continuation indicators in free source form, see Free Source Form; in fixed and tab source forms, see Fixed and Tab Source Forms.
Source Form
All forms Free Fixed Tab
Position
Anywhere in source code At the beginning of the source line In column 1 In column 1
2-7
Source Form
Free Fixed Tab All forms
Position
At the end of the source line In column 6 After the first tab Between statements on the same line Before a statement In columns 1 through 5 Before the first tab In column 1 In column 1
Continuation line2
Statement separator
Statement label
1 to 5 decimal digits
A debugging statement3
Fixed Tab
1. If the character appears in a Hollerith or character constant, it is not an indicator and is ignored. 2. For all forms, up to 511 continuation lines are allowed. 3. Fixed and tab forms only.
Source code can be written so that it is useable for all source forms (see Source Code Useable for All Source Forms).
Statement Labels
A statement label (or statement number) identifies a statement so that other statements can refer to it, either to get information or to transfer control. A label can precede any statement that is not part of another statement. A statement label must be one to five decimal digits long; blanks and leading zeros are ignored. An all-zero statement label is invalid, and a blank statement cannot be labeled. Labeled FORMAT and labeled executable statements are the only statements that can be referred to by other statements. FORMAT statements are referred to only in the format specifier of an I/O statement or in an ASSIGN statement. Two statements within a scoping unit cannot have the same label.
See Also
2-8
Free Source Form for details on labels in free source form Fixed and Tab Source Forms for details on labels in fixed and tab source forms
The blanks are required after INTEGER, TO, 20, and DO. Some adjacent keywords must have one or more blank characters between them. Others do not require any; for example, BLOCK DATA can also be spelled BLOCKDATA. The following list shows which keywords have optional or required blanks:
Optional Blanks
BLOCK DATA DOUBLE COMPLEX DOUBLE PRECISION ELSE IF ELSE WHERE END BLOCK DATA END DO END FILE END FORALL END FUNCTION END IF END INTERFACE END MODULE END PROGRAM END SELECT END SUBROUTINE
Required Blanks
CASE DEFAULT DO WHILE IMPLICIT type-specifier IMPLICIT NONE INTERFACE ASSIGNMENT INTERFACE OPERATOR MODULE PROCEDURE RECURSIVE FUNCTION RECURSIVE SUBROUTINE RECURSIVE type-specifier FUNCTION type-specifier FUNCTION type-specifier RECURSIVE FUNCTION
2-9
Optional Blanks
END TYPE END WHERE GO TO IN OUT SELECT CASE
Required Blanks
For information on statement separators (;) in all forms, see Source Code Useable for All Source Forms.
Comment Indicator
In free source form, the exclamation point character (!) indicates a comment if it is within a source line, or a comment line if it is the first character in a source line.
Continuation Indicator
In free source form, the ampersand character (&) indicates a continuation line (unless it appears in a Hollerith or character constant, or within a comment). The continuation line is the first noncomment line following the ampersand. Although Fortran 95/90 permits up to 39 continuation lines in free-form programs, Intel Fortran allows up to 511 continuation lines. The following shows a continued statement:
TCOSH(Y) = EXP(Y) + & EXP(-Y) ! The initial statement line ! A continuation line
If the first nonblank character on the next noncomment line is an ampersand, the statement continues at the character following the ampersand. For example, the preceding example can be written as follows:
TCOSH(Y) = EXP(Y) + & & EXP(-Y)
If a lexical token must be continued, the first nonblank character on the next noncomment line must be an ampersand followed immediately by the rest of the token. For example:
TCOSH(Y) = EXP(Y) + EX& &P(-Y)
If you continue a character constant, an ampersand must be the first non-blank character of the continued line; the statement continues with the next character following the ampersand. For example:
ADVERTISER = "Davis, OBrien, Chalmers & Peter& &son"
2-10
ARCHITECT
If the ampersand is omitted on the continued line, the statement continues with the first non-blank character in the continued line. So, in the preceding example, the whitespace before "Associates" would be included. The ampersand cannot be the only nonblank character in a line, or the only nonblank character before a comment; an ampersand in a comment is ignored.
See Also
Source Code Useable for All Source Forms for details on the general rules for all source forms
Comment Indicator
In fixed and tab source forms, the exclamation point character (!) indicates a comment if it is within a source line. (It must not appear in column 6 of a fixed form line; that column is reserved for a continuation indicator.) The letter C (or c), an asterisk (*), or an exclamation point (!) indicates a comment line when it appears in column 1 of a source line.
Continuation Indicator
In fixed and tab source forms, a continuation line is indicated by one of the following: For fixed form: Any character (except a zero or blank) in column 6 of a source line For tab form: Any digit (except zero) after the first tab
2-11
The compiler considers the characters following the continuation indicator to be part of the previous line. Although Fortran 95/90 permits up to 19 continuation lines in a fixed-form program, Intel Fortran allows up to 511 continuation lines. If a zero or blank is used as a continuation indicator, the compiler considers the line to be an initial line of a Fortran statement. The statement label field of a continuation line must be blank (except in the case of a debugging statement). When long character or Hollerith constants are continued across lines, portability problems can occur. Use the concatenation operator to avoid such problems. For example:
PRINT *, + This is a very long character constant // which is safely continued across lines
Use this same method when initializing data with long character or Hollerith constants. For example:
CHARACTER*(*) LONG_CONST PARAMETER (LONG_CONST = This is a very long // + character constant which is safely continued // + across lines) CHARACTER*100 LONG_VAL DATA LONG_VAL /LONG_CONST/
Hollerith constants must be converted to character constants before using the concatenation method of line continuation.
2-12
Source Forms for details on the general rules for all source forms, statement separators (;) in all forms, and statement labels Appendix A, Deleted and Obsolescent Language Features, for details on obsolescent features in Fortran 95 Your users guide for details on compiler options
Fixed-Format Lines
In fixed source form, a source line has columns divided into fields for statement labels, continuation indicators, statement text, and sequence numbers. Each column represents a single character. The column positions for each field follow:
Field
Statement label Continuation indicator Statement Sequence number
Column
1 through 5 6 7 through 72 (or 132 with a compiler option) 73 through 80
By default, a sequence number or other identifying information can appear in columns 73 through 80 of any fixed-format line in an Intel Fortran program. The compiler ignores the characters in this field. If you extend the statement field to position 132, the sequence number field does not exist. NOTE. If you use the sequence number field, do not use tabs anywhere in the source line, or the compiler may interpret the sequence numbers as part of the statement field in your program.
See Also Source Forms for details on the general rules for all source forms Fixed and Tab Source Forms for details on the general rules for fixed and tab source forms Tab-Format Lines
In tab source form, you can specify a statement label field, a continuation indicator field, and a statement field, but not a sequence number field. Figure 2-2 shows equivalent source lines coded with tab and fixed source form.
2-13
Figure 2-2
Format using TAB Character 1 C TAB FIRST VALUE 10 TAB I = J + 5*K + TAB 1 L*M TAB IVAL = I+2 C 1 0 2 3 4 5
CharacterperColumn Format 6 7 F I 1 I L 8 I 9 10 11 12 13 14 15 16 17 18 19 20 R S = * M L = I + 2 T J V A + L 5 U E * K +
V A
ZK0614GE
The statement label field precedes the first tab character. The continuation indicator field and statement field follow the first tab character. The continuation indicator is any nonzero digit. The statement field can contain any Fortran statement. A Fortran statement cannot start with a digit. If a statement is continued, a continuation indicator must be the first character (following the first tab) on the continuation line. Many text editors and terminals advance the terminal print carriage to a predefined print position when you press the <Tab> key. However, the Intel Fortran compiler does not interpret the tab character in this way. It treats the tab character in a statement field the same way it treats a blank character. In the source listing that the compiler produces, the tab causes the character that follows to be printed at the next tab stop (usually located at columns 9, 17, 25, 33, and so on). NOTE. If you use the sequence number field, do not use tabs anywhere in the source line, or the compiler may interpret the sequence numbers as part of the statement field in your program.
2-14
See Also Source Forms for details on the general rules for all source forms Fixed and Tab Source Forms for details on the general rules for fixed and tab source forms
2-15
2-16
Each constant, variable, array, expression, or function reference in a Fortran statement has a data type. The data type of these items can be inherent in their construction, implied by convention, or explicitly declared. Each data type has the following properties: A name The names of the intrinsic data types are predefined, while the names of derived types are defined in derived-type definitions. Data objects (constants, variables, or parts of constants or variables) are declared using the name of the data type. A set of associated values Each data type has a set of valid values. Integer and real data types have a range of valid values. Complex and derived types have sets of values that are combinations of the values of their individual components. A way to represent constant values for the data type A constant is a data object with a fixed value that cannot be changed during program execution. The value of a constant can be a numeric value, a logical value, or a character string. A constant that does not have a name is a literal constant. A literal constant must be of intrinsic type and it cannot be array-valued. A constant that has a name is a named constant. A named constant can be of any type, including derived type, and it can be array-valued. A named constant has the PARAMETER attribute and is specified in a type declaration statement or PARAMETER statement. A set of operations to manipulate and interpret these values The data type of a variable determines the operations that can be used to manipulate it. Besides intrinsic operators and operations, you can also define operators and operations. This chapter contains information on the following topics: Intrinsic Data Types (This topic also discusses the forms for constants.)
3-1
Derived Data Types Binary, Octal, Hexadecimal, and Hollerith Constants Variables
See Also Type Declaration Statements Defined Operations Expressions for details on valid operations for data types PARAMETER Attribute and Statement for details on named constants and the PARAMETER attribute Your users guide for details on ranges for numeric literal constants
3-2
DOUBLE COMPLEX (see Complex Data Types) No kind parameter is permitted for data declared with type DOUBLE COMPLEX. This data type is the same as COMPLEX([KIND=]8). LOGICAL (see Logical Data Types) There are four kind parameters for data of type logical: LOGICAL([KIND=]1) or LOGICAL*1 LOGICAL([KIND=]2) or LOGICAL*2 LOGICAL([KIND=]4) or LOGICAL*4 LOGICAL([KIND=]8) or LOGICAL*8 CHARACTER (see Character Data Type) There is one kind parameter for data of type character: CHARACTER([KIND=]1). BYTE This is a 1-byte value; the data type is equivalent to INTEGER([KIND=]1).
The intrinsic function KIND can be used to determine the kind type parameter of a representation method. For more portable programs, you should not use the forms INTEGER([KIND=]n) or REAL([KIND=]n). You should instead define a PARAMETER constant using the SELECTED_INT_KIND or SELECTED_REAL_KIND function, whichever is appropriate. For example, the following statements define a PARAMETER constant for an INTEGER kind that has 9 digits:
INTEGER, PARAMETER :: MY_INT_KIND = SELECTED_INT_KIND(9) ... INTEGER(MY_INT_KIND) :: J ...
Note that syntax separator :: is used in type declaration statements. The following sections describe the intrinsic data types and forms for literal constants for each type.
See Also Type Declaration Statements KIND Declaration Statements for Noncharacter Types and Declaration Statements for Character Types for details on declaration statements for intrinsic data types Expressions for details on operations for intrinsic data types Table 15-2 for details on storage requirements for intrinsic data types
3-3
Integer Constants
An integer constant is a whole number with no decimal point. It can have a leading sign and is interpreted as a decimal number. Integer constants take the following form: [s]n[n...][ _k] s Is a sign; required if negative (), optional if positive (+). n Is a decimal digit (0 through 9). Any leading zeros are ignored. k Is the optional kind parameter: 1 for INTEGER(1), 2 for INTEGER(2), 4 for INTEGER(4), or 8 for INTEGER(8). It must be preceded by an underscore ( _ ). An unsigned constant is assumed to be nonnegative. Integers are expressed in decimal values (base 10) by default. To specify a constant that is not in base 10, use the following syntax: [s][[base] #]nnn... s Is an optional plus (+) or minus () sign.
3-4
base Is any constant from 2 through 36. If base is omitted but # is specified, the integer is interpreted in base 16. If both base and # are omitted, the integer is interpreted in base 10. For bases 11 through 36, the letters A through Z represent numbers greater than 9. For example, for base 36, A represents 10, B represents 11, C represents 12, and so on, through Z, which represents 35. The case of the letters is not significant.
Examples
The following examples show valid and invalid integer (base 10) constants:
Valid
0 -127 +32123 47_2
Invalid
9999999999999999999 3.14 32,767 33_3
Explanation
Number too large. Decimal point not allowed; this is a valid REAL constant. Comma not allowed. 3 is not a valid kind for integers.
The following integers (most of which are not base 10) are all assigned a value equal to 3,994,575 decimal:
I m J K n L index = = = = = = = 2#1111001111001111001111 7#45644664 +8#17171717 #3CF3CF +17#2DE110 3994575 36#2DM8F
You can use integer constants to assign values to data. The following table shows assignments to different data and lists the integer and hexadecimal values in the data:
3-5
Fortran Assignment
LOGICAL(1)X INTEGER(1)X X = 128 X = 127 X = 255 LOGICAL(2)X INTEGER(2)X X = 255 X = 32768 X = 32767 X = 65535
128 127 1
See Also Numeric Expressions for details on integer constants used in expressions Your users guide for details on the ranges for integer types and kinds
3-6
3-7
The exponent letter Q denotes a quad-precision real (REAL(16)) constant. A minus sign must appear before a negative real constant; a plus sign is optional before a positive constant. Similarly, a minus sign must appear between the exponent letter (E, D, or Q) and a negative exponent, whereas a plus sign is optional between the exponent letter and a positive exponent. If the real constant includes an exponent letter, the exponent field cannot be omitted, but it can be zero. To specify a real constant using both an exponent letter and a kind parameter, the exponent letter must be E, and the kind parameter must follow the exponent part.
REAL(4) Constants
A single-precision REAL constant occupies four bytes of memory. The number of digits is unlimited, but typically only the leftmost seven digits are significant. IEEE* S_floating format is used.
Examples
The following examples show valid and invalid REAL(4) constants:
Valid
3.14159 3.14159_4 621712._4 .00127 +5.0E3 2E3_4
Invalid
1,234,567. 325E47 47.E47 625._6 100 $25.00
Explanation
Commas not allowed. Too small for REAL; this is a valid DOUBLE PRECISION constant. Too large for REAL; this is a valid DOUBLE PRECISION constant. 6 is not a valid kind for reals. Decimal point missing; this is a valid integer constant. Special character not allowed.
Your users guide for details on the format and range of REAL(4) data Your users guide for details on compiler options affecting Real data
Examples
The following examples show valid and invalid REAL(8) or DOUBLE PRECISION constants:
Valid
123456789D+5 123456789E+5_8 +2.7843D00 .522D12 2E200_8 2.3_8 3.4E7_8
Invalid
.25D0_2 +2.7182812846182 123456789.D400 123456789.D400
Explanation
2 is not a valid kind for reals. No D exponent designator is present; this is a valid single-precision constant. Too large for any double-precision format. Too small for any double-precision format.
See Also General Rules for Real Constants Your users guide for details on the format and range of DOUBLE PRECISION (REAL(8)) data Your users guide for details on compiler options affecting DOUBLE PRECISION data
3-9
REAL(16) Constants
A REAL(16) constant has more than four times the accuracy of a REAL(4) number, and a greater range. A REAL(16) constant occupies 16 bytes of memory. The number of digits that precede the exponent is unlimited, but typically only the leftmost 33 digits are significant. IEEE X_floating format is used.
Examples
The following examples show valid and invalid REAL(16) constants:
Valid
123456789Q4000 1.23Q400 +2.72Q0 1.88_16
Invalid
1.Q5000 1.Q5000
Explanation
Too large. Too small.
See Also General Rules for Real Constants Your users guide for details on the format and range of REAL(16) data
3-10
If a kind parameter is specified, the complex constant has the kind specified. If no kind parameter is specified, the kind of both parts is default real, and the constant is of type default complex. Default complex is COMPLEX(4). You can change the default behavior by specifying the compiler option that controls the default real kind. DOUBLE COMPLEX is COMPLEX(8). No kind parameter is permitted for data declared with type DOUBLE COMPLEX.
COMPLEX(4) Constants
A COMPLEX(4) constant is a pair of integer or single-precision real constants that represent a complex number. A COMPLEX(4) constant occupies eight bytes of memory and is interpreted as a complex number. If the real and imaginary part of a complex literal constant are both real, the kind parameter value is that of the part with the greater decimal precision. The rules for REAL(4) constants apply to REAL(4) constants used in COMPLEX constants. (See General Rules for Real Constants and REAL(4) Constants for the rules on forming REAL(4) constants.) The REAL(4) constants in a COMPLEX constant have IEEE S_floating format.
Examples
The following examples show valid and invalid COMPLEX(4) constants:
3-11
Valid
(1.7039,1.70391) (44.36_4,12.2E16_4) (+12739E3,0.) (1,2)
Invalid
(1.23,) (1.0, 2H12)
Explanation
Missing second integer or single-precision real constant. Hollerith constant not allowed.
See Also General Rules for Complex Constants Your users guide for details on the format and range of COMPLEX (COMPLEX(4)) data Your users guide for details on compiler options affecting REAL data COMPLEX(8) or DOUBLE COMPLEX Constants
A COMPLEX(8) or DOUBLE COMPLEX constant is a pair of constants that represents a complex number. One of the pair must be a double-precision real constant, the other can be an integer, single-precision real, or double-precision real constant. A COMPLEX(8) or DOUBLE COMPLEX constant occupies 16 bytes of memory and is interpreted as a complex number. The rules for DOUBLE PRECISION (REAL(8)) constants also apply to the double precision portion of COMPLEX(8) or DOUBLE COMPLEX constants. (See General Rules for Real Constants and REAL(8) or DOUBLE PRECISION Constants for the rules on forming DOUBLE PRECISION constants.) The DOUBLE PRECISION constants in a COMPLEX(8) or DOUBLE COMPLEX constant have IEEE T_floating format.
Examples
The following examples show valid and invalid COMPLEX(8) or DOUBLE COMPLEX constants:
Valid
(1.7039,1.7039D0) (547.3E0_8,1.44_8)
3-12
(1.7039E0,1.7039D0) (+12739D3,0.D0)
Invalid
(1.23D0,) (1D1,2H12) (1,1.2)
Explanation
Missing second constant. Hollerith constants not allowed. Neither constant is DOUBLE PRECISION; this is a valid single-precision constant.
See Also General Rules for Complex Constants Your users guide for details on the format and range of DOUBLE COMPLEX data Your users guide for details on compiler options affecting DOUBLE PRECISION data COMPLEX(16) Constants
A COMPLEX(16) constant is a pair of constants that represents a complex number. One of the pair must be a REAL(16) constant, the other can be an integer, single-precision real, double-precision real, or REAL(16) constant. A COMPLEX(16) constant occupies 32 bytes of memory and is interpreted as a complex number. The rules for REAL(16) constants apply to REAL(16) constants used in COMPLEX constants. (See General Rules for Real Constants and REAL(16) Constants for the rules on forming REAL(16) constants.) The REAL(16) constants in a COMPLEX constant have IEEE X_floating format.
Examples
The following examples show valid and invalid COMPLEX(16) constants:
Valid
(1.7039,1.7039Q2) (547.3E0_16,1.44) (+12739Q3,0.Q0)
Invalid
(1.23Q0,) (1D1,2H12) (1.7039,1.7039D0)
Explanation
Missing second constant. Hollerith constants not allowed. Neither constant is REAL(16); this is a valid double-precision constant.
3-13
See Also General Rules for Complex Constants Your users guide for details on the format and range of COMPLEX(16) data Your users guide for details on compiler options affecting REAL data
Logical Constants
A logical constant represents only the logical values true or false, and takes one of the following forms: .TRUE.[_k] .FALSE.[_k] k Is the optional kind parameter: 1 for LOGICAL(1), 2 for LOGICAL(2), 4 for LOGICAL(4), or 8 for LOGICAL(8). It must be preceded by an underscore ( _ ). Logical data type ranges correspond to their comparable integer data type ranges. For example, the LOGICAL(2) range is the same as the INTEGER(2) range.
See Also
Your users guide for details on integer data type ranges
3-14
CHARACTER CHARACTER([KIND=]n) CHARACTER([LEN=]len) CHARACTER([LEN=]len [,[KIND=]n]) CHARACTER(KIND=n [,LEN=len]) CHARACTER*len[,] n Is kind 1. len Is a string length (not a kind). For more information, see Declaration Statements for Character Types. If no kind type parameter is specified, the kind of the constant is default character.
Character Constants
A character constant is a character string enclosed in delimiters (apostrophes or quotation marks). It takes one of the following forms: [k_]'[ch...]' [C] [k_]"[ch...]" [C] k Is the optional kind parameter: 1 (the default). It must be followed by an underscore ( _ ). Note that in character constants, the kind must precede the constant. ch Is an ASCII character. C Is a C string specifier. C strings can be used to define strings with nonprintable characters. For more information, see C Strings in Character Constants.
3-15
The length of the character constant is the number of characters between the delimiters, but two consecutive delimiters are counted as one character. The length of a character constant must be in the range of 0 to 2000. Each character occupies one byte of memory. If a character constant appears in a numeric context (such as an expression on the right side of an arithmetic assignment statement), it is considered a Hollerith constant. A zero-length character constant is represented by two consecutive apostrophes or quotation marks.
Examples
The following examples show valid and invalid character constants:
Valid
"WHAT KIND TYPE? " 'TODAY''S DATE IS: ' "The average is: " ''
Invalid
'HEADINGS 'Map Number: "
Explanation
No trailing apostrophe. Beginning delimiter does not match ending delimiter.
See Also
Declaration Statements for Character Types
3-16
Table 3-1 shows the escape sequences that are allowed in character constants.
Table 3-1 C-Style Escape Sequences Escape Sequence
\a or \A \b or \B \f or \F \n or \N \r or \R \t or \T \v or \V \xhh or \Xhh \ooo \0 \\
Represents
A bell A backspace A formfeed A new line A carriage return A horizontal tab A vertical tab A hexadecimal bit pattern An octal bit pattern A null character A backslash (\)
If a string contains an escape sequence that isn't in this table, the backslash is ignored. A C string must also be a valid Fortran string. If the string is delimited by apostrophes, apostrophes in the string itself must be represented by two consecutive apostrophes (''). For example, the escape sequence \'string causes a compiler error because Fortran interprets the apostrophe as the end of the string. The correct form is \''string. If the string is delimited by quotation marks, quotation marks in the string itself must be represented by two consecutive quotation marks (""). The sequences \ooo and \xhh allow any ASCII character to be given as a one- to three-digit octal or a one- to two-digit hexadecimal character code. Each octal digit must be in the range 0 to 7, and each hexadecimal digit must be in the range 0 to F. For example, the C strings '\010'C and '\x08'C both represent a backspace character followed by a null character. The C string '\\abcd'C is equivalent to the string '\abcd' with a null character appended. The string ''C represents the ASCII null character.
Character Substrings
A character substring is a contiguous segment of a character string. It takes one of the following forms: v ([e1]:[e2]) a (s [,s] . . . ) ([e1]:[e2])
3-17
v Is a character scalar constant, or the name of a character scalar variable or character structure component. e1 Is a scalar integer (or other numeric) expression specifying the leftmost character position of the substring; the starting point. e2 Is a scalar integer (or other numeric) expression specifying the rightmost character position of the substring; the ending point. a Is the name of a character array. s Is a subscript expression. Both e1 and e2 must be within the range 1,2, ..., len, where len is the length of the parent character string. If e1 exceeds e2, the substring has length zero.
Examples
Consider the following example:
CHARACTER*8 C, LABEL LABEL = XVERSUSY' C = LABEL(2:7)
LABEL(2:7) specifies the substring starting with the second character position and ending with the seventh character position of the character variable assigned to LABEL, so C has the value
'VERSUS'.
3-18
TYPE ORGANIZATION INTEGER ID CHARACTER*35 NAME END TYPE ORGANIZATION TYPE(ORGANIZATION) DIRECTOR CHARACTER*25 BRANCH, STATE(50)
3-19
Structure Constructors Derived-Type Assignment Statements Record Structures Defining Generic Operators for details on OPERATOR interfaces Defining Generic Assignment for details on ASSIGNMENT interfaces
Derived-Type Definition
A derived-type definition specifies the name of a user-defined type and the types of its components. It takes the following form: TYPE [ [, access] :: ] name component-definition [component-definition] . . . END TYPE [name] access Is the PRIVATE or PUBLIC keyword. The keyword can only be specified if the derived-type definition is in the specification part of a module. name Is the name of the derived type. It must not be the same as the name of any intrinsic type, or the same as the name of a derived type that can be accessed from a module. component-definition Is one or more type declaration statements defining the component of derived type. The first component definition can be preceded by an optional PRIVATE or SEQUENCE statement. (Only one PRIVATE or SEQUENCE statement can appear in a given derived-type definition.) PRIVATE specifies that the components are accessible only within the defining module, even if the derived type itself is public. SEQUENCE cause the components of the derived type to be stored in the same sequence they are listed in the type definition. If SEQUENCE is specified, all derived types specified in component definitions must be sequence types. A component definition takes the following form: type [ [, attr] ::] component [(a-spec)] [ *char-len] [init-ex]
3-20
type Is a type specifier. It can be an intrinsic type or a previously defined derived type. (If the POINTER attribute follows this specifier, the type can also be any accessible derived type, including the type being defined.) attr Is an optional POINTER attribute for a pointer component, or an optional DIMENSION or ALLOCATABLE attribute for an array component. You cannot specify both the ALLOCATABLE and POINTER attribute. If DIMENSION is specified, it can be followed by an array specification. Each attribute can only appear once in a given component-definition. component Is the name of the component being defined. a-spec Is an optional array specification, enclosed in parentheses. If POINTER or ALLOCATABLE is specified, the array is deferred shape; otherwise, it is explicit shape. In an explicit-shape specification, each bound must be a constant scalar integer expression. For more information on array specifications, see Declaration Statements for Arrays. If the array bounds are not specified here, they must be specified following the DIMENSION attribute. char-len Is an optional scalar integer literal constant; it must be preceded by an asterisk (*). This parameter can only be specified if the component is of type CHARACTER. init-ex Is an initialization expression or, for pointer components, =>NULL( ). This is a Fortran 95 feature. If init-ex is specified, a double colon must appear in the component definition. The equals assignment symbol (=) can only be specified for nonpointer components. The initialization expression is evaluated in the scoping unit of the type definition.
3-21
Two data entities have the same type if they are both declared to be of the same derived type (the derived-type definition can be accessed from a module or a host scoping unit). If the entities are in different scoping units, they can also have the same derived type if they are declared with reference to different derived-type definitions, and if both derived-type definitions have all of the following: The same name A SEQUENCE statement (they both have sequence type) Components that agree in name, order, and attributes; components cannot be private
See Also Intrinsic Data Types Arrays Structure Components Declaration Statements for Derived Types for details on how to declare variables of derived type POINTER Attribute and Statement for details on pointers Default Initializationfor details on default initialization for derived-type components Your users guide for details on alignment of derived-type data components
Default Initialization
Default initialization occurs if initialization appears in a derived-type component definition. (This is a Fortran 95 feature.) The specified initialization of the component will apply even if the definition is PRIVATE. Default initialization applies to dummy arguments with INTENT(OUT). It does not imply the derived-type component has the SAVE attribute. Explicit initialization in a type declaration statement overrides default initialization. To specify default initialization of an array component, use a constant expression that includes one of the following: An array constructor A single scalar that becomes the value of each array element Pointers can have an association status of associated, disassociated, or undefined. If no default initialization status is specified, the status of the pointer is undefined. To specify disassociated status for a pointer component, use =>NULL( ).
3-22
Examples
You do not have to specify initialization for each component of a derived type. For example:
TYPE REPORT CHARACTER (LEN=20) REPORT_NAME INTEGER DAY CHARACTER (LEN=3) MONTH INTEGER :: YEAR = 1995 ! Only component with default END TYPE REPORT ! initialization
In this case, the explicit initialization in the type declaration statement overrides the YEAR component of NOV_REPORT. The default initial value of a component can also be overridden by default initialization specified in the type definition. For example:
TYPE MGR_REPORT TYPE (REPORT) :: STATUS = NOV_REPORT INTEGER NUM END TYPE MGR_REPORT TYPE (MGR_REPORT) STARTUP
In this case, the STATUS component of STARTUP gets its initial value from NOV_REPORT, overriding the initialization for the YEAR component.
Structure Components
A reference to a component of a derived-type structure takes the following form: parent [%component [(s-list)]]... %component [(s-list)] parent Is the name of a scalar or array of derived type. The percent sign (%) is called a component selector. component Is the name of a component of the immediately preceding parent or component. s-list Is a list of one or more subscripts. If the list contains subscript triplets or vector subscripts, the reference is to an array section.
3-23
Each subscript must be a scalar integer (or other numeric) expression with a value that is within the bounds of its dimension. The number of subscripts in any s-list must equal the rank of the immediately preceding parent or component.
Examples
The following example shows a derived-type definition with two components:
TYPE EMPLOYEE INTEGER ID CHARACTER(LEN=40) NAME END TYPE EMPLOYEE
Note that both examples started with the keyword TYPE. The first (initial) statement of a derived-type definition is called a derived-type statement, while the statement that declares a derived- type object is called a TYPE statement. The following example shows how to reference component ID of parent structure CONTRACT:
CONTRACT%ID
The following example shows a derived type with a component that is a previously defined type:
TYPE DOT REAL X, Y END TYPE DOT ....
3-24
Variable M has components M%C and M%D (both of type DOT); M%C has components M%C%X and M%C%Y of type REAL. The following example shows a derived type with a component that is an array:
TYPE CAR_INFO INTEGER YEAR CHARACTER(LEN=15), DIMENSION(10) :: MAKER CHARACTER(LEN=10) MODEL, BODY_TYPE*8 REAL PRICE END TYPE ... TYPE(CAR_INFO) MY_CAR
Note that MODEL has a character length of 10, but BODY_TYPE has a character length of 8. You can assign a value to a component of a structure; for example:
MY_CAR%YEAR = 1985
In the preceding example, if a subscript list (or substring) was appended to MAKER, the reference would not be to an array structure component, but to an array element or section. Consider the following:
MY_CAR%MAKER(2) (4:10)
In this case, the component is substring 4 to 10 of the second element of array MAKER. Consider the following:
TYPE CHARGE INTEGER PARTS(40) REAL LABOR REAL MILEAGE END TYPE CHARGE TYPE(CHARGE) MONTH TYPE(CHARGE) YEAR(12)
3-25
! ! ! ! ! ! !
An An An An An An An
element section structure component (a whole array) element section section section
The following example shows a derived type with a pointer component that is of the type being defined:
TYPE NUMBER INTEGER NUM TYPE(NUMBER), POINTER :: START_NUM => NULL() TYPE(NUMBER), POINTER :: NEXT_NUM => NULL() END TYPE
A type such as this can be used to construct linked lists of objects of type NUMBER. Note that the pointers are given the default initialization status of disassociated. The following example shows a private type:
TYPE, PRIVATE :: SYMBOL LOGICAL TEST CHARACTER(LEN=50) EXPLANATION END TYPE SYMBOL
This type is private to the module. The module can be used by another scoping unit, but type SYMBOL is not available.
See Also Array Elements for details on references to array elements Array Sections for details on references to array sections Modules and Module Procedures for examples of derived types in modules
Structure Constructors
A structure constructor lets you specify scalar values of a derived type. It takes the following form: d-name (expr-list) d-name Is the name of the derived type.
3-26
expr-list Is a list of expressions specifying component values. The values must agree in number and order with the components of the derived type. If necessary, values are converted (according to the rules of assignment), to agree with their corresponding components in type and kind parameters.
Examples
Consider the following derived-type definition:
TYPE EMPLOYEE INTEGER ID CHARACTER(LEN=40) NAME END TYPE EMPLOYEE
In this case, you must use an embedded structure constructor to specify the values of that component; for example:
3-27
See Also
Pointer Assignments
Binary Constants
A binary constant is an alternative way to represent a numeric constant. A binary constant takes one of the following forms: B'd[d...]' B"d[d...]" d Is a binary (base 2) digit (0 or 1). You can specify up to 256 binary digits in a binary constant. Leading zeros are ignored.
Examples
The following examples show valid and invalid binary constants:
Valid
B'0101110' B"1"
Invalid
B'0112' B10011' "1000001"
Explanation
The character 2 is invalid. No apostrophe after the B. No B before the first quotation mark.
3-28
Octal Constants
An octal constant is an alternative way to represent numeric constants. An octal constant takes one of the following forms: O'd[d...]' O"d[d...]" d Is an octal (base 8) digit (0 through 7). You can specify up to 256 bits (86 octal digits) in octal constants. Leading zeros are ignored.
Examples
The following examples show valid and invalid octal constants:
Valid
O'07737' O"1"
Invalid
O'7782' O7772' "0737"
Explanation
The character 8 is invalid. No apostrophe after the O. No O before the first quotation mark.
See Also
Alternative Syntax for Octal and Hexadecimal Constants
Hexadecimal Constants
A hexadecimal constant is an alternative way to represent numeric constants. A hexadecimal constant takes one of the following forms: Z'd[d...]' Z"d[d...]" d Is a hexadecimal (base 16) digit (0 through 9, or an uppercase or lowercase letter in the range of A to F). You can specify up to 256 bits (64 hexadecimal digits) in hexadecimal constants. Leading zeros are ignored.
3-29
Examples
The following examples show valid and invalid hexadecimal constants:
Valid
Z'AF9730' Z"FFABC" Z'84'
Invalid
Z'999.' "ZF9"
Explanation
Decimal not allowed. No quotation mark after the Z.
See Also
Alternative Syntax for Octal and Hexadecimal Constants
Hollerith Constants
A Hollerith constant is a string of printable ASCII characters preceded by the letter H. Before the H, there must be an unsigned, nonzero default integer constant stating the number of characters in the string (including blanks and tabs). Hollerith constants are strings of 1 to 2000 characters. They are stored as byte strings, one character per byte.
Examples
The following examples show valid and invalid Hollerith constants:
Valid
16HTODAY'S DATE IS: 1HB 4H ABC
Invalid
3HABCD 0H
Explanation
Wrong number of characters. Hollerith constants must contain at least one character.
3-30
Length of Constant1
REAL(4) REAL(4) REAL(4) REAL(8) REAL(8) REAL(8) INTEGER(2) INTEGER(2) INTEGER(2) INTEGER(4) INTEGER(4) INTEGER(4)
4 4 4 8 8 8 2 2 2 4 4 4
When a specific data type (generally integer) is required, that type is assumed for the constant. For example:
Statement
Y(1X) = Y (O'15') + 3 Y(1X) = Y (1HA) + 3
1. In bytes.
Length of Constant1
4 4
3-31
Statement
For binary, octal, and hexadecimal constants, INTEGER(8) is assumed on Intel Itanium processors. On IA-32 processors, INTEGER(4) is used. For Hollerith constants, no data type is assumed.
For example:
Data Type of Constant
INTEGER(4) None
Length of Constant1
4 9
When a binary, octal, or hexadecimal constant is used in any other context, the default integer data type is assumed (default integer can be affected by compiler options). In the following examples, default integer is INTEGER(4):
Statement
IF (Z'AF77') 1,2,3 IF (2HAB) 1,2,3 I = O'7777' Z'A39' 2 I = 1HC 1HA J = .NOT. O'73777' J = .NOT. 1HB
1. In bytes. 2. When two typeless constants are used in an operation, they both take default integer type.
Length of Constant1
4 4 4 4 4 4
When nondecimal constants are not the same length as the length implied by a data type, the following occurs: Binary, octal, and hexadecimal constants These constants can specify up to 16 bytes of data. When the length of the constant is less than the length implied by the data type, the leftmost digits have a value of zero. When the length of the constant is greater than the length implied by the data type, the constant is truncated on the left. An error results if any nonzero digits are truncated. Table 15-2 lists the number of bytes that each data type requires. Hollerith constants When the length of the constant is less than the length implied by the data type, blanks are appended to the constant on the right.
3-32
When the length of the constant is greater than the length implied by the data type, the constant is truncated on the right. If any characters other than blank characters are truncated, an error occurs. Each Hollerith character occupies one byte of memory.
See Also
Your users guide for details on compiler options
Variables
A variable is a data object whose value can be changed at any point in a program. A variable can be any of the following: A scalar A scalar is a single object that has a single value; it can be of any intrinsic or derived (user-defined) type. An array An array is a collection of scalar elements of any intrinsic or derived type. All elements must have the same type and kind parameters. A subobject designator A subobject is part of an object. The following are subobjects: An array element An array section A structure component A character substring
For example, B(3) is a subobject (array element) designator for array B. A subobject cannot be a variable if its parent object is a constant. The name of a variable is associated with a single storage location. Variables are classified by data type, as constants are. The data type of a variable indicates the type of data it contains, including its precision, and implies its storage requirements. When data of any type is assigned to a variable, it is converted to the data type of the variable (if necessary). A variable is defined when you give it a value. A variable can be defined before program execution by a DATA statement or a type declaration statement. During program execution, variables can be defined or redefined in assignment statements and input statements, or undefined (for example, if an I/O error occurs). When a variable is undefined, its value is unpredictable. When a variable becomes undefined, all variables associated by storage association also become undefined.
3-33
See Also Arrays Type Declaration Statements DATA Statement Data Type of Numeric Expressions Storage Association for details on storage association of variables
You can explicitly specify the data type of a scalar variable only once. If no explicit data type specification appears, any variable with a name that begins with the letter in the range specified in the IMPLICIT statement becomes the data type of the variable. Character type declaration statements specify that given variables represent character values with the length specified. For example, the following statements associate the variable names INLINE, NAME, and NUMBER with storage locations containing character data of lengths 72, 12, and 9, respectively:
CHARACTER*72 INLINE CHARACTER NAME*12, NUMBER*9
In single subprograms, assumed-length character arguments can be used to process character strings with different lengths. The assumed-length character argument has its length specified with an asterisk, for example:
CHARACTER*(*) CHARDUMMY
3-34
See Also Type Declaration Statements Declaration Statements for Character Types Assumed-Length Character Arguments IMPLICIT Statement Implicit Typing Rules
By default, all scalar variables with names beginning with I, J, K, L, M, or N are assumed to be default integer variables. Scalar variables with names beginning with any other letter are assumed to be default real variables. For example:
Real Variables
ALPHA BETA TOTAL_NUM
Integer Variables
JCOUNT ITEM_1 NTOTAL
Names beginning with a dollar sign ($) are implicitly INTEGER. You can override the default data type implied in a name by specifying data type in either an IMPLICIT statement or a type declaration statement.
Arrays
An array is a set of scalar elements that have the same type and kind parameters. Any object that is declared with an array specification is an array. Arrays can be declared by using a type declaration statement, or by using a DIMENSION, COMMON, ALLOCATABLE, POINTER, or TARGET statement. An array can be referenced by element (using subscripts), by section (using a section subscript list), or as a whole. A subscript list (appended to the array name) indicates which array element or array section is being referenced. A section subscript list consists of subscripts, subscript triplets, or vector subscripts. At least one subscript in the list must be a subscript triplet or vector subscript. When an array name without any subscripts appears in an intrinsic operation (for example, addition), the operation applies to the whole array (all elements in the array).
3-35
An array has the following properties: Data type An array can have any intrinsic or derived type. The data type of an array (like any other variable) is specified in a type declaration statement or implied by the first letter of its name. All elements of the array have the same type and kind parameters. If a value assigned to an individual array element is not the same as the type of the array, it is converted to the array's type. Rank The rank of an array is the number of dimensions in the array. An array can have up to seven dimensions. A rank-one array represents a column of data (a vector), a rank-two array represents a table of data arranged in columns and rows (a matrix), a rank-three array represents a table of data on multiple pages (or planes), and so forth. Bounds Arrays have a lower and upper bound in each dimension. These bounds determine the range of values that can be used as subscripts for the dimension. The value of either bound can be positive, negative, or zero. The bounds of a dimension are defined in an array specification. Size The size of an array is the total number of elements in the array (the product of the array's extents). The extent is the total number of elements in a particular dimension. It is determined as follows: upper bound lower bound + 1. If the value of any of an array's extents is zero, the array has a size of zero. Shape The shape of an array is determined by its rank and extents, and can be represented as a rank-one array (vector) where each element is the extent of the corresponding dimension. Two arrays with the same shape are said to be conformable. A scalar is conformable to an array of any shape. The name and rank of an array must be specified when the array is declared. The extent of each dimension can be constant, but does not need to be. The extents can vary during program execution if the array is a dummy argument array, an automatic array, an array pointer, or an allocatable array. A whole array is referenced by the array name. Individual elements in a named array are referenced by a scalar subscript or list of scalar subscripts (if there is more than one dimension). A section of a named array is referenced by a section subscript.
3-36
Examples
The following are examples of valid array declarations:
DIMENSION A(10, 2, 3) ALLOCATABLE B(:, :) POINTER C(:, :, :) REAL, DIMENSION (2, 5) :: D INTEGER L(2:11,3) ! ! ! ! DIMENSION statement ALLOCATABLE statement POINTER statement Type declaration with DIMENSION attribute
Consider the following array declaration: The properties of array L are as follows:
Data type: Rank: Bounds: Size: Shape: INTEGER 2 (two dimensions) First dimension: 2 to 11 Second dimension: 1 to 3 30; the product of the extents: 10 x 3 (/10,3/) (or 10 by 3); a vector of the extents 10 and 3
The following example shows other valid ways to declare this array:
DIMENSION L(2:11,3) INTEGER, DIMENSION(2:11,3) :: L COMMON L(2:11,3)
The following example shows references to array elements, array sections, and a whole array:
REAL B(10) INTEGER C(5,8) ... B(3) = 5.0 B(2:5) = 1.0 ... C(4,8) = I C(1:3,3:4) = J ! Declares a rank-one array with 10 elements ! Declares a rank-two array with 5 elements in ! dimension one and 8 elements in dimension two ! Reference to an array element ! Reference to an array section consisting of ! elements: B(2), B(3), B(4), B(5) ! Reference to an array element ! Reference to an array section consisting of ! elements: C(1,3) C(1,4) ! C(2,3) C(2,4) ! C(3,3) C(3,4)
3-37
B = 99
! Reference to a whole array consisting of ! elements: B(1), B(2), B(3), B(4), B(5), ! B(6), B(7), B(8), B(9), and B(10)
See Also DIMENSION Attribute and Statement Intrinsic Data Types Derived Data Types Whole Arrays Array Elements Array Sections Declaration Statements for Arrays for details on array specifications Table 9-2 for details on intrinsic functions that perform array operations Whole Arrays
A whole array is a named array; it is either a named constant or a variable. It is referenced by using the array name (without any subscripts). If a whole array appears in a nonexecutable statement, the statement applies to the entire array. For example:
INTEGER, DIMENSION(2:11,3) :: L ! Specifies the type and ! dimensions of array L
If a whole array appears in an executable statement, the statement applies to all of the elements in the array. For example:
L = 10 WRITE *, L ! The value 10 is assigned to all the ! elements in array L ! Prints all the elements in array L
Array Elements
An array element is one of the scalar data items that make up an array. A subscript list (appended to the array or array component) determines which element is being referred to. A reference to an array element takes the following form: array(subscript-list) array Is the name of the array.
3-38
subscript-list Is a list of one or more subscripts separated by commas. The number of subscripts must equal the rank of the array. Each subscript must be a scalar integer (or other numeric) expression with a value that is within the bounds of its dimension.
However, by convention, such an object is considered to be a substring rather than an array element. The following are some valid array element references for an array declared as REAL B(10,20): B(1,3), B(10,10), and B(5,8). For information on forms for array specifications, see Declaration Statements for Arrays.
3-39
3
.
Figure 3-1
Array Storage
OneDimensional Array BRC (6) 1 BRC(1) 2 BRC(2) 3 BRC(3) 4 BRC(4) 5 BRC(5) 6 BRC(6)
Memory Positions TwoDimensional Array BAN (3,4) 1 2 3 BAN(1,1) BAN(2,1) BAN(3,1) 4 5 6 BAN(1,2) BAN(2,2) BAN(3,2) 7 8 9 BAN(1,3) 10 BAN(2,3) 11 BAN(3,3) 12 BAN(1,4) BAN(2,4) BAN(3,4)
Memory Positions ThreeDimensional Array BOS (3,3,3) 19 20 10 11 1 2 3 BOS(1,1,1) BOS(2,1,1) BOS(3,1,1) BOS(1,1,2) BOS(2,1,2) BOS(1,1,3) BOS(2,1,3) 22 23 BOS(1,2,3) BOS(2,2,3) 25 26 27 BOS(1,3,3) BOS(2,3,3) BOS(3,3,3)
Memory Positions
ZK0616GE
For example, in two-dimensional array BAN, element BAN(1,2) has a subscript order value of 4; in three-dimensional array BOS, element BOS(1,1,1) has a subscript order value of 1.
3-40
In an array section, the subscript order of the elements is their order within the section itself. For example, if an array is declared as B(20), the section B(4:19:4) consists of elements B(4), B(8), B(12), and B(16). The subscript order value of B(4) in the array section is 1; the subscript order value of B(12) in the section is 3.
See Also Character Substrings Array Association Structure Components for details on arrays as structure components Storage Association for details on storage sequence association Array Sections
An array section is a portion of an array that is an array itself. It is an array subobject. A section subscript list (appended to the array or array component) determines which portion is being referred to. A reference to an array section takes the following form: array(sect-subscript-list) array Is the name of the array. sect-subscript-list Is a list of one or more section subscripts (subscripts, subscript triplets, or vector subscripts) indicating a set of elements along a particular dimension. At least one of the items in the section subscript list must be a subscript triplet or vector subscript. A subscript triplet specifies array elements in increasing or decreasing order at a given stride. A vector subscript specifies elements in any order. Each subscript and subscript triplet must be a scalar integer (or other numeric) expression. Each vector subscript must be a rank-one integer expression.
3-41
Each array section inherits the type, kind type parameter, and certain attributes (INTENT, PARAMETER, and TARGET) of the parent array. An array section cannot inherit the POINTER attribute. If an array (or array component) is of type character, it can be followed by a substring range in parentheses. Consider the following declaration:
CHARACTER(LEN=15) C(10,10)
In this case, an array section referenced as C(:,:) (1:3) is an array of shape (10,10), whose elements are substrings of length 3 of the corresponding elements of C. The following shows valid references to array sections. Note that the syntax (/.../) denotes an array constructor (see Array Constructors):
REAL, DIMENSION(20) :: B ... PRINT *, B(2:20:5) ! The section consists of elements ! B(2), B(7), B(12), and B(17) K = (/3, 1, 4/) B(K) = 0.0 ! Section B(K) is a rank-one array with shape (3) and ! size 3. (0.0 is assigned to B(1), B(3), and B(4).)
Subscript Triplets
A subscript triplet is a set of three values representing the lower bound of the array section, the upper bound of the array section, and the increment (stride) between them. It takes the following form: [first-bound] : [last-bound] [:stride] first-bound Is a scalar integer (or other numeric) expression representing the first value in the subscript sequence. If omitted, the declared lower bound of the dimension is used. last-bound Is a scalar integer (or other numeric) expression representing the last value in the subscript sequence. If omitted, the declared upper bound of the dimension is used. When indicating sections of an assumed-size array, this subscript must be specified. stride Is a scalar integer (or other numeric) expression representing the increment between successive subscripts in the sequence. It must have a nonzero value. If it is omitted, it is assumed to be 1. The stride has the following effects:
3-42
If the stride is positive, the subscript range starts with the first subscript and is incremented by the value of the stride, until the largest value less than or equal to the second subscript is attained. For example, if an array has been declared as B(6,3,2), the array section specified as B(2:4,1:2,2) is a rank-two array with shape (3,2) and size 6. It consists of the following six elements:
B(2,1,2) B(3,1,2) B(4,1,2) B(2,2,2) B(3,2,2) B(4,2,2)
If the first subscript is greater than the second subscript, the range is empty. If the stride is negative, the subscript range starts with the value of the first subscript and is decremented by the absolute value of the stride, until the smallest value greater than or equal to the second subscript is attained. For example, if an array has been declared as A(15), the array section specified as A(10:3:-2) is a rank-one array with shape (4) and size 4. It consists of the following four elements:
A(10) A(8) A(6) A(4)
If the second subscript is greater than the first subscript, the range is empty. If a range specified by the stride is empty, the array section has a size of zero. A subscript in a subscript triplet need not be within the declared bounds for that dimension if all values used to select the array elements are within the declared bounds. For example, if an array has been declared as A(15), the array section specified as A(4:16:10) is valid. The section is a rank-one array with shape (2) and size 2. It consists of elements A(4) and A(14). If the subscript triplet does not specify bounds or stride, but only a colon (:), the entire declared range for the dimension is used.
Vector Subscripts
A vector subscript is a one-dimensional (rank one) array of integer values (within the declared bounds for the dimension) that selects a section of a whole (parent) array. The elements in the section do not have to be in order and the section can contain duplicate values. For example, A is a rank-two array of shape (4,6). B and C are rank- one arrays of shape (2) and (3), respectively, with the following values:
B = (/1,4/) C = (/2,1,1/) ! Syntax (/.../) denotes an array constructor ! Will result in a many-one array section
3-43
Array section A(3,B) consists of elements A(3,1) and A(3,4). Array section A(C,1) consists of elements A(2,1), A(1,1), and A(1,1). Array section A(B,C) consists of the following elements:
A(1,2) A(4,2) A(1,1) A(4,1) A(1,1) A(4,1)
An array section with a vector subscript that has two or more elements with the same value is called a many-one array section. A many-one section must not appear on the left of the equal sign in an assignment statement, or as an input item in a READ statement. The following assignments to C also show examples of vector subscripts:
INTEGER A(2), B(2), C(2) ... B = (/1,2/) C(B) = A(B) C = A((/1,2/))
An array section with a vector subscript must not be any of the following: An internal file An actual argument associated with a dummy array that is defined or redefined (if the INTENT attribute is specified, it must be INTENT(IN)) The target in a pointer assignment statement If the sequence specified by the vector subscript is empty, the array section has a size of zero.
See Also INTENT Attribute and Statement PARAMETER Attribute and Statement TARGET Attribute and Statement Character Substrings Array Constructors Structure Components for details on array sections as structure components Array Constructors
An array constructor can be used to create and assign values to rank-one arrays (and array constants). An array constructor takes the following form: (/ac-value-list/) ac-value-list Is a list of one or more expressions or implied-DO loops. Each ac-value must have the same type and kind parameters, and be separated by commas.
3-44
An implied-DO loop in an array constructor takes the following form: (ac-value-list, do-variable = expr1, expr2 [, expr3]) do-variable Is the name of a scalar integer variable. Its scope is that of the implied-DO loop. expr Is a scalar integer expression. The expr1 and expr2 specify a range of values for the loop; expr3 specifies the stride. The expr3 must be a nonzero value; if it is omitted, it is assumed to be 1.
A scalar expression
An array expression
An implied-DO loop
If every expression in an array constructor is a constant expression, the array constructor is a constant expression. If the expressions are of type character, Fortran 95/90 requires each expression to have the same character length. However, Intel Fortran allows the character expressions to be of different character lengths. The length of the resultant character array is the maximum of the lengths of the individual character expressions. For example:
print *,len ( (/'a','ab','abc','d'/) )
3-45
print *,'++'//(/'a','ab','abc','d'/)//'--'
If an implied-DO loop is contained within another implied-DO loop (nested), they cannot have the same DO variable (do-variable). To define arrays of more than one dimension, use the RESHAPE intrinsic function. The following are alternative forms for array constructors: Square brackets (instead of parentheses and slashes) to enclose array constructors; for example, the following two array constructors are equivalent:
INTEGER C(4) C = (/4,8,7,6/) C = [4,8,7,6]
A colon-separated triplet (instead of an implied-DO loop) to specify a range of values and a stride; for example, the following two array constructors are equivalent:
INTEGER D(3) D = (/1:5:2/) D = (/(I, I=1, 5, 2)/) ! Triplet form ! implied-DO loop form
Examples
The following example shows an array constructor using an implied-DO loop:
INTEGER ARRAY_C(10) ARRAY_C = (/(I, I=30, 48, 2)/)
The values of ARRAY_C are the even numbers 30 through 48. The following example shows an array constructor of derived type that uses a structure constructor:
TYPE EMPLOYEE INTEGER ID CHARACTER(LEN=30) NAME END TYPE EMPLOYEE TYPE(EMPLOYEE) CC_4T(4) CC_4T = (/EMPLOYEE(2732,"JONES"), EMPLOYEE(0217,"LEE"), & EMPLOYEE(1889,"RYAN"), EMPLOYEE(4339,"EMERSON")/)
The following example shows how the RESHAPE intrinsic function can be used to create a multidimensional array:
3-46
E = (/2.3, 4.7, 6.6/) D = RESHAPE(SOURCE = (/3.5, (/2.0, 1.0/), E/), SHAPE = (/2,3/))
See Also DO Constructs RESHAPE Subscript Triplets Derived Data Types Structure Constructors Array Elements for details on array element order Array Assignment Statements for details on another way to assign values to arrays Declaration Statements for Arrays for details on array specifications
3-47
3-48
Expressions
An expression represents either a data reference or a computation, and is formed from operators, operands, and parentheses. The result of an expression is either a scalar value or an array of scalar values. If the value of an expression is of intrinsic type, it has a kind type parameter. (If the value is of intrinsic type CHARACTER, it also has a length parameter.) If the value of an expression is of derived type, it has no kind type parameter. An operand is a scalar or array. An operator can be either intrinsic or defined. An intrinsic operator is known to the compiler and is always available to any program unit. A defined operator is described explicitly by a user in a function subprogram and is available to each program unit that uses the subprogram. The simplest form of an expression (a primary) can be any of the following: A constant; for example, 4.2 A subobject of a constant; for example, 'LMNOP' (2:4) A variable; for example, VAR_1 A structure constructor; for example, EMPLOYEE(3472, "JOHN DOE") An array constructor; for example, (/12.0,16.0/) A function reference; for example, COS(X) Another expression in parentheses; for example, (I+5)
4-1
Any variable or function reference used as an operand in an expression must be defined at the time the reference is executed. If the operand is a pointer, it must be associated with a target object that is defined. An integer operand must be defined with an integer value rather than a statement label value. All of the characters in a character data object reference must be defined. When a reference to an array or an array section is made, all of the selected elements must be defined. When a structure is referenced, all of the components must be defined. In an expression that has intrinsic operators with an array as an operand, the operation is performed on each element of the array. In expressions with more than one array operand, the arrays must be conformable (they must have the same shape). The operation is applied to corresponding elements of the arrays, and the result is an array of the same shape (the same rank and extents) as the operands. In an expression that has intrinsic operators with a pointer as an operand, the operation is performed on the value of the target associated with the pointer. For defined operators, operations on arrays and pointers are determined by the procedure defining the operation. A scalar is conformable with any array. If one operand of an expression is an array and another operand is a scalar, it is as if the value of the scalar were replicated to form an array of the same shape as the array operand. The result is an array of the same shape as the array operand. The following sections describe numeric, character, relational, and logical expressions; defined operations; a summary of operator precedence; and initialization and specification expressions.
See Also Arrays Derived Data Types Defining Generic Operators for details on function subprograms that define operators POINTER Attribute and Statement for details on pointers
Numeric Expressions
Numeric expressions express numeric computations, and are formed with numeric operands and numeric operators. The evaluation of a numeric operation yields a single numeric value. The term numeric includes logical data, because logical data is treated as integer data when used in a numeric context. The default for .TRUE. is 1; .FALSE. is 0. The default can change if a specific compiler option is used. Numeric operators specify computations to be performed on the values of numeric operands. The result is a scalar numeric value or an array whose elements are scalar numeric values. The following are numeric operators:
4-2
Operator ** *
/ +
Function
Exponentiation Multiplication Division Addition or unary plus (identity) Subtraction or unary minus (negation)
Unary operators operate on a single operand. Binary operators operate on a pair of operands. The plus and minus operators can be unary or binary. When they are unary operators, the plus or minus operators precede a single operand and denote a positive (identity) or negative (negation) value, respectively. The exponentiation, multiplication, and division operators are binary operators. Valid numeric operations must have results that are defined by the arithmetic used by the processor. For example, raising a negative-valued base to a real power is invalid. Numeric expressions are evaluated in an order determined by a precedence associated with each operator, as follows (see also Summary of Operator Precedence):
Operator ** * and /
Unary + and Binary + and
Precedence
Highest . . Lowest
Operators with equal precedence are evaluated in left-to-right order. However, exponentiation is evaluated from right to left. For example, A**B**C is evaluated as A**(B**C). B**C is evaluated first, then A is raised to the resulting power. Normally, two operators cannot appear together. However, Intel Fortran allows two consecutive operators if the second operator is a plus or minus.
Examples
In the following example, the exponentiation operator is evaluated first because it takes precedence over the multiplication operator:
A**B*C is evaluated as (A**B)*C
Ordinarily, the exponentiation operator would be evaluated first in the following example. However, because Intel Fortran allows the combination of the exponentiation and minus operators, the exponentiation operator is not evaluated until the minus operator is evaluated:
4-3
Note that the multiplication operator is evaluated first, since it takes precedence over the minus operator. When consecutive operators are used with constants, the unary plus or minus before the constant is treated the same as any other operator. This can produce unexpected results. In the following example, the multiplication operator is evaluated first, since it takes precedence over the minus operator:
X/-15.0*Y is evaluated as X/-(15.0*Y)
= 11
= 2
= 4
Expressions within parentheses are evaluated according to the normal order of precedence. In expressions containing nested parentheses, the innermost parentheses are evaluated first. Nonessential parentheses do not affect expression evaluation, as shown in the following example:
4 + (3 * 2) - (6/2)
4-4
However, using parentheses to specify the evaluation order is often important in high-accuracy numerical computations. In such computations, evaluation orders that are algebraically equivalent may not be computationally equivalent when processed by a computer (because of the way intermediate results are rounded off). Parentheses can be used in argument lists to force a given argument to be treated as an expression, rather than as the address of a memory item.
Ranking
Lowest . . . . . . . . . . . .
2
Highest
The data type of the value produced by an operation on two numeric operands of different data types is the data type of the highest- ranking operand in the operation. For example, the value resulting from an operation on an integer and a real operand is of real type. However, an operation involving a COMPLEX(4) or COMPLEX(8) data type and a DOUBLE PRECISION data type produces a COMPLEX(8) result.
4-5
The data type of an expression is the data type of the result of the last operation in that expression, and is determined according to the following conventions: Integer operations: Integer operations are performed only on integer operands. (Logical entities used in a numeric context are treated as integers.) In integer arithmetic, any fraction resulting from division is truncated, not rounded. For example, the result of 1/4 + 1/4 + 1/4 + 1/4 is 0, not 1. Real operations: Real operations are performed only on real operands or combinations of real, integer, and logical operands. Any integer operands present are converted to real data type by giving each a fractional part equal to zero. The expression is then evaluated using real arithmetic. However, in the statement Y = (I /J)*X, an integer division operation is performed on I and J, and a real multiplication is performed on that result and X. If one operand is a higher-precision real (REAL(8) or REAL(16)) type, the other operand is converted to that higher-precision real type before the expression is evaluated. When a single-precision real operand is converted to a double-precision real operand, low-order binary digits are set to zero. This conversion does not increase accuracy; conversion of a decimal number does not produce a succession of decimal zeros. For example, a REAL variable having the value 0.3333333 is converted to approximately 0.3333333134651184D0. It is not converted to either 0.3333333000000000D0 or 0.3333333333333333D0. Complex operations: In operations that contain any complex operands, integer operands are converted to real type, as previously described. The resulting single-precision or double-precision operand is designated as the real part of a complex number and the imaginary part is assigned a value of zero. The expression is then evaluated using complex arithmetic and the resulting value is of complex type. Operations involving a COMPLEX(4) or COMPLEX(8) operand and a DOUBLE PRECISION operand are performed as COMPLEX(8) operations; the DOUBLE PRECISION operand is not rounded. These rules also generally apply to numeric operations in which one of the operands is a constant. However, if a real or complex constant is used in a higher-precision expression, additional precision will be retained for the constant. The effect is as if a DOUBLE PRECISION (REAL(8)) or REAL(16) representation of the constant were given. For example, the expression 1.0D0 + 0.3333333 is treated as if it is 1.0D0 + 0.3333333000000000D0.
Character Expressions
A character expression consists of a character operator (//) that concatenates two operands of type character. The evaluation of a character expression produces a single value of that type.
4-6
The result of a character expression is a character string whose value is the value of the left character operand concatenated to the value of the right operand. The length of a character expression is the sum of the lengths of the values of the operands. For example, the value of the character expression AB//CDE is ABCDE, which has a length of five. Parentheses do not affect the evaluation of a character expression; for example, the following character expressions are equivalent:
(ABC//DE)//F ABC//(DE//F) ABC//DE//F
Each of these expressions has the value ABCDEF. If a character operand in a character expression contains blanks, the blanks are included in the value of the character expression. For example, ABC //D E//F has a value of ABC D EF .
Relational Expressions
A relational expression consists of two or more expressions whose values are compared to determine whether the relationship stated by the relational operator is satisfied. The following are relational operators:
Operator
.LT. .LE. .EQ. .NE. .GT. .GE. or or or or or or < <= == /= > >=
Relationship
Less than Less than or equal to Equal to Not equal to Greater than Greater than or equal to
The result of the relational expression is .TRUE. if the relation specified by the operator is satisfied; the result is .FALSE. if the relation specified by the operator is not satisfied. Relational operators are of equal precedence. Numeric operators and the character operator // have a higher precedence than relational operators. In a numeric relational expression, the operands are numeric expressions. Consider the following example:
APPLE+PEACH > PEAR+ORANGE
4-7
This expression states that the sum of APPLE and PEACH is greater than the sum of PEAR and ORANGE. If this relationship is valid, the value of the expression is .TRUE.; if not, the value is .FALSE.. Operands of type complex can only be compared using the equal operator (= = or .EQ.) or the not equal operator (/= or .NE.). Complex entities are equal if their corresponding real and imaginary parts are both equal. In a character relational expression, the operands are character expressions. In character relational expressions, less than (< or .LT.) means the character value precedes in the ASCII collating sequence, and greater than (> or .GT.) means the character value follows in the ASCII collating sequence. For example:
'AB'//'ZZZ' .LT. 'CCCCC'
This expression states that 'ABZZZ' is less than 'CCCCC'. In this case, the relation specified by the operator is satisfied, so the result is .TRUE.. Character operands are compared one character at a time, in order, starting with the first character of each operand. If the two character operands are not the same length, the shorter one is padded on the right with blanks until the lengths are equal; for example:
'ABC' .EQ. 'ABC 'AB' .LT. 'C' '
The first relational expression has the value .TRUE. even though the lengths of the expressions are not equal, and the second has the value .TRUE. even though 'AB' is longer than 'C'. A relational expression can compare two numeric expressions of different data types. In this case, the value of the expression with the lower-ranking data type is converted to the higher-ranking data type before the comparison is made.
See Also
Data Type of Numeric Expressions for details on the ranking of data types
Logical Expressions
A logical expression consists of one or more logical operators and logical, numeric, or relational operands. The following are logical operators:
Operator
.AND. .OR.
Example
A .AND. B A .OR. B
Meaning
Logical conjunction: the expression is true if both A and B are true. Logical disjunction (inclusive OR): the expression is true if either A, B, or both, are true.
4-8
Operator
.NEQV. .XOR. .EQV. .NOT.1
Example
A .NEQV. B A .XOR. B A .EQV. B .NOT. A
Meaning
Logical inequivalence (exclusive OR): the expression is true if either A or B is true, but false if both are true. Same as .NEQV. Logical equivalence: the expression is true if both A and B are true, or both are false. Logical negation: the expression is true if A is false and false if A is true.
Periods cannot appear consecutively except when the second operator is .NOT. For example, the following logical expression is valid:
A+B/(A-1) .AND. .NOT. D+B/(D-1)
As with numeric expressions, you can use parentheses to alter the sequence of evaluation. When operators have equal precedence, the compiler can evaluate them in any order, as long as the result is the same as the result gained by the algebraic left-to-right order of evaluation (except for exponentiation, which is evaluated from right to left).
4-9
You should not write logical expressions whose results might depend on the evaluation order of subexpressions. The compiler is free to evaluate subexpressions in any order. In the following example, either (A(I)+1.0) or B(I)*2.0 could be evaluated first:
(A(I)+1.0) .GT. B(I)*2.0
Some subexpressions might not be evaluated if the compiler can determine the result by testing other subexpressions in the logical expression. Consider the following expression:
A .AND. (F(X,Y) .GT. 2.0) .AND. B
If the compiler evaluates A first, and A is false, the compiler might determine that the expression is false and might not call the subprogram F(X,Y).
See Also
Summary of Operator Precedence for details on the precedence of numeric, relational, and logical operators
Defined Operations
When operators are defined for functions, the functions can then be referenced as defined operations. The operators are defined by using a generic interface block specifying OPERATOR, followed by the defined operator (in parentheses). A defined operation is not an intrinsic operation. However, you can use a defined operation to extend the meaning of an intrinsic operator. For defined unary operations, the function must contain one argument. For defined binary operations, the function must contain two arguments. Interpretation of the operation is provided by the function that defines the operation. A Fortran 95/90 defined operator can contain up to 31 letters, and is enclosed in periods (.). Its name cannot be the same name as any of the following: The intrinsic operators (.NOT., .AND., .OR., .XOR., .EQV., .NEQV., .EQ., .NE., .GT., .GE., .LT., and .LE.) The logical literal constants (.TRUE. or .FALSE.). An intrinsic operator can be followed by a defined unary operator. The result of a defined operation can have any type. The type of the result (and its value) must be specified by the defining function. The following examples show expressions containing defined operators:
.COMPLEMENT. A X .PLUS. Y .PLUS. Z
4-10
M * .MINUS. N
Operator
Defined unary operators ** * or / Unary + or Binary + or // .EQ., .NE., .LT., .LE., .GT., .GE. = =, /=, <, <=, >, >= .NOT. .AND. .OR. .XOR., .EQV., .NEQV. Defined binary operators
Precedence
Highest . . . . . . . . . . Lowest
4-11
Initialization Expressions
An initialization expression must evaluate at compile time to a constant. It is used to specify an initial value for an entity. In an initialization expression, each operation is intrinsic and each operand is one of the following: A constant or subobject of a constant An array constructor where each element and the bounds and strides of each implied-DO, are expressions whose primaries are initialization expressions A structure constructor whose components are initialization expressions An elemental intrinsic function reference of type integer or character, whose arguments are initialization expressions of type integer or character A reference to one of the following inquiry functions: BIT_SIZE DIGITS EPSILON HUGE ILEN KIND LBOUND LEN MAXEXPONENT MINEXPONENT PRECISION RADIX RANGE SHAPE SIZE TINY UBOUND
Each function argument must be one of the following: An initialization expression A variable whose kind type parameter and bounds are not assumed or defined by an ALLOCATE statement, pointer assignment, or an expression that is not an initialization expression A reference to one of the following transformational functions (each argument must be an initialization expression): functions: REPEAT RESHAPE SELECTED_INT_KIND SELECTED_REAL_KIND TRANSFER TRIM
A reference to the transformational function NULL An implied-DO variable within an array constructor where the bounds and strides of the corresponding implied-DO are initialization expressions
4-12
Each subscript, section subscript, and substring starting and ending point must be an initialization expression. In an initialization expression, the exponential operator (**) must have a power of type integer. If an initialization expression invokes an inquiry function for a type parameter or an array bound of an object, the type parameter or array bound must be specified in a prior specification statement (or to the left of the inquiry function in the same statement).
Examples
The following examples show valid and invalid initialization (constant) expressions:
Valid
1 + 3 SIZE(B) 7_2 INT(J, 4) SELECTED_INT_KIND (2) ! J is a named constant ! B is a named constant
Invalid
SUM(A) A/4.1 K**1.2 HUGE(4.0)
Explanation
Not an allowed function. Exponential does not have integer power (A and K are named constants). Argument is not an integer.
See Also Array Constructors Structure Constructors Intrinsic Procedures for details on intrinsic functions Specification Expressions
A specification expression is a restricted expression that is of type integer and has a scalar value. This type of expression appears only in the declaration of array bounds and character lengths. In a restricted expression, each operation is intrinsic and each operand is one of the following: A constant or subobject of a constant A variable that is one of the following:
4-13
A dummy argument that does not have the OPTIONAL or INTENT (OUT) attribute (or the subobject of such a variable) In a common block (or the subobject of such a variable) Made accessible by use or host association (or the subobject of such a variable) A structure constructor whose components are restricted expressions An implied-DO variable within an array constructor where the bounds and strides of the corresponding implied-DO are restricted expressions A reference to one of the following inquiry functions: BIT_SIZE DIGITS EPSILON HUGE ILEN KIND LBOUND LEN MAXEXPONENT MINEXPONENT PRECISION RADIX RANGE SHAPE SIZE SIZEOF TINY UBOUND
Each function argument must be one of the following: A restricted expression A variable whose properties inquired about are not dependent on the upper bound of the last dimension of an assumed-size array, are not defined by an expression that is not a restricted expression, or are not definable by an ALLOCATE or pointer assignment statement. A reference to any other intrinsic function where each argument is a restricted expression. A reference to a specification function where each argument is a restricted expression An array constructor where each element and the bounds and strides of each implied-DO, are expressions whose primaries are restricted expressions Another restricted expression enclosed in parentheses
Each subscript, section subscript, and substring starting and ending point must be a restricted expression. Specification functions can be used in specification expressions to indicate the attributes of data objects. A specification function is a pure function. It cannot have a dummy procedure argument or be any of the following: An intrinsic function
4-14
A variable in a specification expression must have its type and type parameters (if any) specified in one of the following ways: By a previous declaration in the same scoping unit By the implicit typing rules currently in effect for the scoping unit By host or use association If a variable in a specification expression is typed by the implicit typing rules, its appearance in any subsequent type declaration statement must confirm the implied type and type parameters. If a specification expression invokes an inquiry function for a type parameter or an array bound of an object, the type parameter or array bound must be specified in a prior specification statement (or to the left of the inquiry function in the same statement). In a specification expression, the number of arguments for a function reference is limited to 255.
Examples
The following shows valid specification expressions:
MAX(I) + J UBOUND(ARRAY_B,20) ! I and J are scalar integer variables ! ARRAY_B is an assumed-shape dummy array
See Also Array Constructors Implicit Typing Rules Structure Constructors Use and Host Association Pure Procedures Chapter 9, Intrinsic Procedures, for details on intrinsic functions
Assignment Statements
An assignment statement causes variables to be defined or redefined. This section describes the following kinds of assignment statements: intrinsic, defined, pointer, masked array (WHERE), and element array (FORALL). The ASSIGN statement assigns a label to an integer variable. It is discussed in The ASSIGN and Assigned GO TO Statements.
4-15
Intrinsic Assignments
Intrinsic assignment is used to assign a value to a nonpointer variable. In the case of pointers, intrinsic assignment is used to assign a value to the target associated with the pointer variable. The value assigned to the variable (or target) is determined by evaluation of the expression to the right of the equal sign. An intrinsic assignment statement takes the following form: variable = expression variable Is the name of a scalar or array of intrinsic or derived type (with no defined assignment). The array cannot be an assumed-size array, and neither the scalar nor the array can be declared with the PARAMETER or INTENT(IN) attribute. expression Is of intrinsic type or the same derived type as variable. Its shape must conform with variable. If necessary, it is converted to the same type and kind as variable.
If the variable is a pointer, it must be associated with a definable target. The shape of the target and expression must conform and their type and kind parameters must match. The following sections discuss numeric, logical, character, derived- type, and array intrinsic assignment.
See Also Arrays Derived Data Types Defining Generic Assignment for details on subroutine subprograms that define assignment
4-16
Complex
V=INT(REAL(E)) Imaginary part of E is not used. V=REAL(REAL(E)) Imaginary part of E is not used. V=DBLE(REAL(E)) Imaginary part of E is not used. V=QEXT(REAL(E)) Imaginary part of E is not used. V=CMPLX(REAL(REAL(E)), REAL(AIMAG(E)))
4-17
Examples
The following examples show valid and invalid numeric assignment statements:
Valid
BETA = -1./(2.*X)+A*A /(4.*(X*X)) PI = 3.14159 SUM = SUM + 1. ARRAY_A = ARRAY_B + ARRAY_C + SCALAR_I ! Valid if all arrays conform in shape.
Invalid
3.14 = A B ICOUNT = A//B(3:7) SCALAR_I = ARRAY_A(:)
Explanation
Entity on the left must be a variable. Implicitly typed data types do not match. Shapes do not match.
See Also INT REAL DBLE QEXT CMPLX AIMAG Logical Assignment Statements
For logical assignment statements, the variable must be of logical type and the expression can be of logical or numeric type. If necessary, the expression is converted to the same type and kind as the variable.
Examples
The following examples show valid logical assignment statements:
PAGEND = .FALSE. PRNTOK = LINE .LE. 132 .AND. .NOT. PAGEND ABIG = A.GT.B .AND. A.GT.C .AND. A.GT.D LOGICAL_VAR = 123 ! Moves binary value of 123 to LOGICAL_VAR
4-18
The variable and expression can have different lengths. If the length of the expression is greater than the length of the variable, the character expression is truncated on the right. If the length of the expression is less than the length of the variable, the character expression is filled on the right with blank characters. If you assign a value to a character substring, you do not affect character positions in any part of the character scalar variable not included in the substring. If a character position outside of the substring has a value previously assigned, it remains unchanged. If the character position is undefined, it remains undefined.
Examples
The following examples show valid and invalid character assignment statements. (In the valid examples, all variables are of type character.)
Valid
FILE = 'PROG2' REVOL(1) = 'MAR'//'CIA' LOCA(3:8) = 'PLANT5' TEXT(I,J+1)(2:N-1) = NAME/ /X
Invalid
'ABC'= CHARS CHARS = 25 STRING = 5HBEGIN
Explanation
Left element must be a character variable, array element, or substring reference. Expression does not have a character data type. Expression does not have a character data type. (Hollerith constants are numeric, not character.)
Examples
The following example shows derived-type assignment:
4-19
TYPE DATE LOGICAL(1) DAY, MONTH INTEGER(2) YEAR END TYPE DATE TYPE(DATE) TODAY, THIS_WEEK(7) TYPE APPOINTMENT ... TYPE(DATE) APP_DATE END TYPE TYPE(APPOINTMENT) MEETING DO I = 1,7 CALL GET_DATE(TODAY) THIS_WEEK(I) = TODAY END DO MEETING%APP_DATE = TODAY
See Also Derived Data Types Pointer Assignments Array Assignment Statements
Array assignment is permitted when the array expression on the right has the same shape as the array variable on the left, or the expression on the right is a scalar. If the expression is a scalar, and the variable is an array, the scalar value is assigned to every element of the array. If the expression is an array, the variable must also be an array. The array element values of the expression are assigned (element by element) to corresponding elements of the array variable. A many-one array section is a vector-valued subscript that has two or more elements with the same value. In intrinsic assignment, the variable cannot be a many-one array section because the result of the assignment is undefined.
Examples
In the following example, X and Y are arrays of the same shape:
X = Y
4-20
The corresponding elements of Y are assigned to those of X element by element; the first element of Y is assigned to the first element of X, and so forth. The processor can perform the element-by-element assignment in any order. The following example shows a scalar assigned to an array:
B(C+1:N, C) = 0
This sets the elements B (C+1,C), B (C+2,C),...B (N,C) to zero. The following example causes the values of the elements of array A to be reversed:
REAL A(20) ... A(1:20) = A(20:1:-1)
See Also Arrays WHERE Statement and Construct for details on masked array assignment FORALL Statement and Construct for details on element array assignment
Defined Assignments
Defined assignment specifies an assignment operation. It is defined by a subroutine subprogram containing a generic interface block with the specifier ASSIGNMENT(=). The subroutine is specified by a SUBROUTINE or ENTRY statement that has two nonoptional dummy arguments. Defined elemental assignment is indicated by specifying ELEMENTAL in the SUBROUTINE statement. The dummy arguments represent the variable and expression, in that order. The rank (and shape, if either or both are arrays), type, and kind parameters of the variable and expression in the assignment statement must match those of the corresponding dummy arguments. The dummy arguments must not both be numeric, or of type logical or character with the same kind parameter. If the variable in an elemental assignment is an array, the defined assignment is performed element-by-element, in any order, on corresponding elements of the variable and expression. If the expression is scalar, it is treated as if it were an array of the same shape as the variable with every element of the array equal to the scalar value of the expression.
See Also Derived Data Types Subroutines for details on subroutine subprograms Defining Generic Assignment for details on subroutine subprograms that define assignment Numeric Expressions and Character Expressions for details on intrinsic operations
4-21
Pointer Assignments
In ordinary assignment involving pointers, the pointer is an alias for its target. In pointer assignment, the pointer is associated with a target. If the target is undefined or disassociated, the pointer acquires the same status as the target. The pointer assignment statement has the following form: pointer-object => target pointer-object Is a variable name or structure component declared with the POINTER attribute. target Is a variable or expression. Its type and kind parameters, and rank must be the same as pointer-object. It cannot be an array section with a vector subscript.
Examples
The following are examples of pointer assignments:
4-22
HOUR => MINUTES(1:60) M_YEAR => MY_CAR%YEAR NEW_ROW%RIGHT => CURRENT_ROW PTR => M POINTER_C => NULL () INTEGER, POINTER :: P, N INTEGER, TARGET :: M INTEGER S M = 14 N => M P => N S = P + 5
! ! ! ! !
target is an array target is a structure component pointer object is a structure component target is a variable reference to NULL intrinsic
See Also Arrays Defined Assignments NULL POINTER Attribute and Statement for details on pointers Chapter 6, Dynamic Allocation, for details on the ALLOCATE, DEALLOCATE, and NULLIFY statements Intrinsic Assignments for details on derived-type intrinsic assignments
4-23
[ELSE WHERE [name] [where-body-stmt]...] END WHERE [name] mask-expr1, mask-expr2 Are logical array expressions (called mask expressions). assign-stmt Is an assignment statement of the form: array variable = array expression. name Is the name of the WHERE construct. where-body-stmt Is one of the following: An assign-stmt The assignment can be a defined assignment only if the routine implementing the defined assignment is elemental. A WHERE statement or construct
4-24
The assignment statement is only executed for those elements where the mask is true. Think of the mask expression as being evaluated first into a logical array that has the value true for those elements where A is positive. This array of trues and falses is applied to the arrays A, B and C in the assignment statement. The right side is only evaluated for elements for which the mask is true; assignment on the left side is only performed for those elements for which the mask is true. The elements for which the mask is false do not get assigned a value. In a WHERE construct, the mask expression is evaluated first and only once. Every assignment statement following the WHERE is executed as if it were a WHERE statement with "mask-expr1" and every assignment statement following the ELSE WHERE is executed as if it were a WHERE statement with ".NOT. mask-expr1". If ELSE WHERE specifies "mask-expr2", it is executed as "(.NOT. mask-expr1) .AND. mask-expr2" during the processing of the ELSE WHERE statement. You should be careful if the statements have side effects, or modify each other or the mask expression. The following is an example of the WHERE construct:
DIMENSION PRESSURE(1000), TEMP(1000), PRECIPITATION(1000) WHERE(PRESSURE .GE. 1.0) PRESSURE = PRESSURE + 1.0 TEMP = TEMP - 10.0 ELSEWHERE PRECIPITATION = .TRUE. ENDWHERE
The mask is applied to the arguments of functions on the right side of the assignment if they are considered to be elemental functions. Only elemental intrinsics are considered elemental functions. Transformational intrinsics, inquiry intrinsics, and functions or operations defined in the subprogram are considered to be nonelemental functions. Consider the following example using LOG, an elemental function:
WHERE(A .GT. 0) B = LOG(A)
The mask is applied to A, and LOG is executed only for the positive values of A. The result of the LOG is assigned to those elements of B where the mask is true. Consider the following example using SUM, a nonelemental function:
REAL A, B DIMENSION A(10,10), B(10) WHERE(B .GT. 0.0) B = SUM(A, DIM=1)
Since SUM is nonelemental, it is evaluated fully for all of A. Then, the assignment only happens for those elements for which the mask evaluated to true. Consider the following example:
4-25
REAL A, B, C DIMENSION A(10,10), B(10), C(10) WHERE(C .GT. 0.0) B = SUM(LOG(A), DIM=1)/C
Because SUM is nonelemental, all of its arguments are evaluated fully regardless of whether they are elemental or not. In this example, LOG(A) is fully evaluated for all elements in A even though LOG is elemental. Notice that the mask is applied to the result of the SUM and to C to determine the right side. One way of thinking about this is that everything inside the argument list of a nonelemental function does not use the mask, everything outside does.
See Also
FORALL Statement and Construct for details on a generalized form of masked array assignment
4-26
mask-expr Is a logical array expression (called the mask expression). If it is omitted, the value .TRUE. is assumed. The mask expression can reference the subscript name in triplet-spec. assign-stmt Is an assignment statement or a pointer assignment statement. It may be a scalar or array assignment statement, or a defined assignment statement. The variable being defined will normally use each subscript-name in the triplet-spec. name Is the name of the FORALL construct. forall-body-stmt Is one of the following: An assign-stmt A WHERE statement or construct The WHERE statement and construct use a mask to make the array assignments (see WHERE Statement and Construct). A FORALL statement or construct
4-27
Examples
Consider the following:
FORALL(I = 1:N, J = 1:N, A(I, J) .NE. 0.0) B(I, J) = 1.0 / A(I, J)
This statement takes the reciprocal of each nonzero element of array A(1:N, 1:N) and assigns it to the corresponding element of array B. Elements of A that are zero do not have their reciprocal taken, and no assignments are made to corresponding elements of B. Every array assignment statement and WHERE statement can be written as a FORALL statement, but some FORALL statements cannot be written using just array syntax. For example, the preceding FORALL statement is equivalent to the following:
WHERE(A /= 0.0) B = 1.0 / A
However, the following FORALL example cannot be written using just array syntax:
FORALL(I = 1:N, J = 1:N) H(I, J) = 1.0/REAL(I + J - 1)
This statement sets array element H(I, J) to the value 1.0 /REAL(I + J - 1) for values of I and J between 1 and N. Consider the following:
TYPE MONARCH INTEGER, POINTER :: P END TYPE MONARCH TYPE(MONARCH), DIMENSION(8) :: PATTERN INTEGER, DIMENSION(8), TARGET :: OBJECT FORALL(J=1:8) PATTERN(J)%P => OBJECT(1+IEOR(J-1,2))
This FORALL statement causes elements 1 through 8 of array PATTERN to point to elements 3, 4, 1, 2, 7, 8, 5, and 6, respectively, of OBJECT. IEOR can be referenced here because it is pure. The following example shows a FORALL construct:
FORALL(I = 3:N + 1, J = 3:N + 1) C(I, J) = C(I, J + 2) + C(I, J - 2) + C(I + 2, J) + C(I - 2, J) D(I, J) = C(I, J) END FORALL
The assignment to array D uses the values of C computed in the first statement in the construct, not the values before the construct began execution.
4-28
See Also Subscript Triplets Pointer Assignments WHERE Statement and Construct Pure Procedures
4-29
4-30
Specification Statements
A specification statement is a nonexecutable statement that declares the attributes of data objects. In Fortran 95/90, many of the attributes that can be defined in specification statements can also be optionally specified in type declaration statements. This chapter contains information on the following topics: Type Declaration Statements Explicitly specifies the properties (for example: data type, rank, and extent) of data objects. ALLOCATABLE Attribute and Statement Specifies a list of array names that are allocatable (have a deferred-shape). AUTOMATIC and STATIC Attributes and Statements Control the storage allocation of variables in subprograms. COMMON Statement Defines one or more contiguous areas, or blocks, of physical storage (called common blocks). DATA Statement Assigns initial values to variables before program execution. DIMENSION Attribute and Statement Specifies that an object is an array, and defines the shape of the array. EQUIVALENCE Statement Specifies that a storage area is shared by two or more objects in a program unit. EXTERNAL Attribute and Statement Allows external (user-supplied) procedures to be used as arguments to other subprograms. IMPLICIT Statement Overrides the implicit data type of names. INTENT Attribute and Statement Specifies the intended use of a dummy argument.
5-1
INTRINSIC Attribute and Statement Allows intrinsic procedures to be used as arguments to subprograms. NAMELIST Statement Associates a name with a list of variables. This group name can be referenced in some input/output operations. OPTIONAL Attribute and Statement Allows a procedure reference to omit arguments. PARAMETER Attribute and Statement Defines a named constant. POINTER Attribute and Statement Specifies that an object is a pointer. PRIVATE and PUBLIC Attributes and Statements Declare the accessibility of entities in a module. SAVE Attribute and Statement Causes the definition and status of objects to be retained after the subprogram in which they are declared completes execution. TARGET Attribute and Statement Specifies a pointer target. VOLATILE Attribute and Statement Prevents optimizations from being performed on specified objects.
See Also
Chapter 8, Program Units and Procedures, for details on BLOCK DATA and PROGRAM statements
5-2
Specification Statements
In the optional kind selector "([KIND=]k) ", k is the kind parameter. It must be an acceptable kind parameter for that data type. If the kind selector is not present, entities declared are of default type. (For a list of the valid noncharacter data types, see Table 5-2.) Kind parameters for intrinsic numeric and logical data types can also be specified using the *n format, where n is the length (in bytes) of the entity; for example, INTEGER*4. att Is one of the following attribute specifiers: ALLOCATABLE AUTOMATIC DIMENSION EXTERNAL INTENT INTRINSIC OPTIONAL PARAMETER
1. These are access specifiers.
v Is the name of a data object or function. It can optionally be followed by: An array specification, if the object is an array. In a function declaration, an array must be a deferred-shape array if it has the POINTER attribute; otherwise, it must be an explicit-shape array. A character length, if the object is of type character. An initialization expression or, for pointer objects, => NULL( ).
A function name must be the name of an intrinsic function, external function, function dummy procedure, or statement function. c-list Is a list of constants, as in a DATA statement. If v is the name of a constant or an initialization expression, the c-list cannot be present.
5-3
The c-list cannot specify more than one value unless it initializes an array. When initializing an array, the c-list must contain a value for every element in the array.
The same attribute must not appear more than once in a given type declaration statement, and an entity cannot be given the same attribute more than once in a scoping unit. If the PARAMETER attribute is specified, the declaration must contain an initialization expression. If => NULL( ) is specified for a pointer, its initial association status is disassociated. A variable (or variable subobject) can only be initialized once in an executable program. If a declaration contains an initialization expression, but no PARAMETER attribute is specified, the object is a variable whose value is initially defined. The object becomes defined with the value determined from the initialization expression according to the rules of intrinsic assignment. The presence of initialization implies that the name of the object is saved, except for objects in named common blocks or objects with the PARAMETER attribute. The following objects cannot be initialized in a type declaration statement: A dummy argument A function result An object in a named common block (unless the type declaration is in a block data program unit) An object in blank common An allocatable array An external name An intrinsic name An automatic object An object that has the AUTOMATIC attribute
5-4
Specification Statements
An object can have more than one attribute. Table 5-1 lists the compatible attributes.
Table 5-1 Attribute
ALLOCATABLE AUTOMATIC DIMENSION EXTERNAL INTENT INTRINSIC OPTIONAL PARAMETER POINTER PRIVATE PUBLIC SAVE STATIC TARGET VOLATILE
1. With deferred shape
Examples
The following show valid type declaration statements:
DOUBLE PRECISION B(6) INTEGER(KIND=2) I REAL(KIND=4) X, Y REAL(4) X, Y LOGICAL, DIMENSION(10,10) :: ARRAY_A, ARRAY_B
5-5
INTEGER, PARAMETER :: SMALLEST = SELECTED_REAL_KIND(6, 70) REAL(KIND (0.0)) M COMPLEX(KIND=8) :: D TYPE(EMPLOYEE) :: MANAGER REAL, INTRINSIC :: COS CHARACTER(15) PROMPT CHARACTER*12, SAVE :: HELLO_MSG INTEGER COUNT, MATRIX(4,4), SUM LOGICAL*2 SWITCH REAL :: X = 2.0 TYPE (NUM), POINTER :: FIRST => NULL()
See Also Derived Data Types Implicit Typing Rules DATA Statement Initialization Expressions Intrinsic Data Types for details on specific kind parameters of intrinsic data types
5-6
Specification Statements
Table 5-2
1. Same as INTEGER(1). 2. This is treated as default logical. 3. This is treated as default integer. 4. This is treated as default real. 5. This is treated as default complex.
In noncharacter type declaration statements, you can optionally specify the name of the data object or function as v*n, where n is the length (in bytes) of v. The length specified overrides the length implied by the data type. The value for n must be a valid length for the type of v (see Table 15-2). The type specifiers BYTE, DOUBLE PRECISION, and DOUBLE COMPLEX have one valid length, so the n specifier is invalid for them. For an array specification, the n must be placed immediately following the array name; for example, in an INTEGER declaration statement, IVEC*2(10) is an INTEGER(2) array of 10 elements.
Examples
In a noncharacter type declaration statement, a subsequent kind parameter overrides any initial kind parameter. For example, consider the following statements:
INTEGER(2) I, J, K, M12*4, Q, IVEC*4(10) REAL(8) WX1, WXZ, WX3*4, WX5, WX6*4 REAL(8) PI/3.14159E0/, E/2.72E0/, QARRAY(10)/5*0.0,5*1.0/
In the first statement, M12*4 and IVEC*4 override the KIND=2 specification. In the second statement, WX3*4 and WX6*4 override the KIND=8 specification. In the third statement, QARRAY is initialized with implicit conversion of the REAL(4) constants to a REAL(8) data type.
See Also Type Declaration Statements for details on the general form and rules for type declaration statements
5-7
Your users guide for details on compiler options that can affect the defaults for numeric and logical data types
5-8
Specification Statements
The length specified for a character-valued statement function or statement function dummy argument of type character must be an integer constant expression. When an asterisk length specification *(*) is used for a function name or dummy argument, it assumes the length of the corresponding function reference or actual argument. Similarly, when an asterisk length specification is used for a named constant, the name assumes the length of the actual constant it represents. For example, STRING assumes a 9-byte length in the following statements:
CHARACTER*(*) STRING PARAMETER (STRING = VALUE IS:)
A function name must not be declared with a * length if the function is an internal or module function, or if it is array-valued, pointer-valued, recursive, or pure. The form CHARACTER*(*) is an obsolescent feature in Fortran 95.
Examples
The following example declares an array NAMES containing 100 32-character elements, an array SOCSEC containing 100 9-character elements, and a variable NAMETY that is 10 characters long and has an initial value of 'ABCDEFGHIJ'.
CHARACTER*32 NAMES(100),SOCSEC(100)*9,NAMETY*10 /ABCDEFGHIJ/
The following example includes a CHARACTER statement declaring two 8-character variables, LAST and FIRST.
INTEGER, PARAMETER :: LENGTH=4 CHARACTER*(4+LENGTH) LAST, FIRST
The following example shows a CHARACTER statement declaring an array LETTER containing 26 one-character elements. It also declares a dummy argument BUBBLE that has a passed length defined by the calling program.
SUBROUTINE S1(BUBBLE) CHARACTER LETTER(26), BUBBLE*(*)
See Also Type Declaration Statements for details on the general form and rules for type declaration statements Specification of Data Type and Assumed-Length Character Arguments for details on asterisk length specifications
5-9
Appendix A, Deleted and Obsolescent Language Features, for details on obsolescent features in Fortran 95
Examples
The following are examples of derived-type declaration statements:
TYPE(EMPLOYEE) CONTRACT ... TYPE(SETS), DIMENSION(:,:), ALLOCATABLE :: SUBSET_1
See Also Derived Data Types Use and Host Association PRIVATE and PUBLIC Attributes and Statements Structure Constructors Type Declaration Statements for details on the general form and rules for type declaration statements
5-10
Specification Statements
a-spec Is one of the following array specifications: Explicit-Shape Specifications Assumed-Shape Specifications Assumed-Size Specifications Deferred-Shape Specifications The array specification can be appended to the name of the array when the array is declared.
Examples
The following examples show array declarations:
SUBROUTINE SUB(N, C, D, Z) REAL, DIMENSION(N, 15) :: IARRY REAL C(:), D(0:) REAL, POINTER :: B(:,:) REAL, ALLOCATABLE, DIMENSION(:) :: K REAL :: Z(N,*) ! ! ! ! ! An explicit-shape array An assumed-shape array A deferred-shape array pointer A deferred-shape allocatable array An assumed-size array
See Also
Type Declaration Statements for details on the general form and rules for type declaration statements
Explicit-Shape Specifications
An explicit-shape array is declared with explicit values for the bounds in each dimension of the array. An explicit-shape specification takes the following form: ([dl:] du[, [dl:] du]...) dl Is a specification expression indicating the lower bound of the dimension. The expression can have a positive, negative, or zero value. If necessary, the value is converted to integer type. If the lower bound is not specified, it is assumed to be 1. du Is a specification expression indicating the upper bound of the dimension. The expression can have a positive, negative, or zero value. If necessary, the value is converted to integer type. The bounds can be specified as constant or nonconstant expressions, as follows:
5-11
If the bounds are constant expressions, the subscript range of the array in a dimension is the set of integer values between and including the lower and upper bounds. If the lower bound is greater than the upper bound, the range is empty, the extent in that dimension is zero, and the array has a size of zero. If the bounds are nonconstant expressions, the array must be declared in a procedure. The bounds can have different values each time the procedure is executed, since they are determined when the procedure is entered. The bounds are not affected by any redefinition or undefinition of the variables in the specification expression that occurs while the procedure is executing. The following explicit-shape arrays can specify nonconstant bounds: An automatic array (the array is a local variable) An adjustable array (the array is a dummy argument to a subprogram)
Automatic Arrays
An automatic array is an explicit-shape array that is a local variable. Automatic arrays are only allowed in function and subroutine subprograms, and are declared in the specification part of the subprogram. At least one bound of an automatic array must be a nonconstant specification expression. The bounds are determined when the subprogram is called. The following example shows automatic arrays:
SUBROUTINE SUB1 (A, B) INTEGER A, B, LOWER COMMON /BOUND/ LOWER ... INTEGER AUTO_ARRAY1(B) ... INTEGER AUTO_ARRAY2(LOWER:B) .. INTEGER AUTO_ARRAY3(20, B*A/2) END SUBROUTINE
5-12
Specification Statements
Adjustable Arrays
An adjustable array is an explicit-shape array that is a dummy argument to a subprogram. At least one bound of an adjustable array must be a nonconstant specification expression. The bounds are determined when the subprogram is called. The array specification can contain integer variables that are either dummy arguments or variables in a common block. When the subprogram is entered, each dummy argument specified in the bounds must be associated with an actual argument. If the specification includes a variable in a common block, the variable must have a defined value. The array specification is evaluated using the values of the actual arguments, as well as any constants or common block variables that appear in the specification. The size of the adjustable array must be less than or equal to the size of the array that is its corresponding actual argument. To avoid possible errors in subscript evaluation, make sure that the bounds expressions used to declare multidimensional adjustable arrays match the bounds as declared by the caller. In the following example, the function computes the sum of the elements of a rank-two array. Notice how the dummy arguments M and N control the iteration:
FUNCTION THE_SUM(A, M, N) DIMENSION A(M, N) SUMX = 0.0 DO J = 1, N DO I = 1, M SUMX = SUMX + A(I, J) END DO END DO THE_SUM = SUMX END FUNCTION
The following example shows how the array bounds determined when the procedure is entered do not change during execution:
DIMENSION ARRAY(9,5) L = 9 M = 5
5-13
CALL SUB(ARRAY,L,M) END SUBROUTINE SUB(X,I,J) DIMENSION X(-I/2:I/2,J) X(I/2,J) = 999 J = 1 I = 2 END
The assignments to I and J do not affect the declaration of adjustable array X as X(4:4,5) on entry to subroutine SUB.
See Also
Specification Expressions
Assumed-Shape Specifications
An assumed-shape array is a dummy argument array that assumes the shape of its associated actual argument array. An assumed-shape specification takes the following form: ([dl]:[, [dl]:]...) dl Is a specification expression indicating the lower bound of the dimension. The expression can have a positive, negative, or zero value. If necessary, the value is converted to integer type. If the lower bound is not specified, it is assumed to be 1. The rank of the array is the number of colons ( : ) specified. The value of the upper bound is the extent of the corresponding dimension of the associated actual argument array + lower-bound 1. The following is an example of an assumed-shape specification:
INTERFACE SUBROUTINE SUB(M) INTEGER M(:, 1:, 5:) END SUBROUTINE END INTERFACE INTEGER L(20, 5:25, 10) CALL SUB(L)
5-14
Specification Statements
Array M has the same extents as array L, but array M has bounds (1:20, 1:21, 5:14). Note that an explicit interface is required when calling a routine that expects an assumed-shape or pointer array.
Assumed-Size Specifications
An assumed-size array is a dummy argument array that assumes the size (only) of its associated actual argument array; the rank and extents can differ for the actual and dummy arrays. An assumed-size specification takes the following form: ([expli-shape-spec,] [expli-shape-spec,]... [dl:] *) expli-shape-spec Is an explicit-shape specification (see Explicit-Shape Specifications). dl Is a specification expression indicating the lower bound of the dimension. The expression can have a positive, negative, or zero value. If necessary, the value is converted to integer type. <p> If the lower bound is not specified, it is assumed to be 1. * Is the upper bound of the last dimension. The rank of the array is the number of explicit-shape specifications plus 1. The size of the array is assumed from the actual argument associated with the assumed-size dummy array as follows: If the actual argument is an array of type other than default character, the size of the dummy array is the size of the actual array. If the actual argument is an array element of type other than default character, the size of the dummy array is a + 1 - s, where s is the subscript order value and a is the size of the actual array. If the actual argument is a default character array, array element, or array element substring, and it begins at character storage unit b of an array with n character storage units, the size of the dummy array is as follows:
MAX(INT((n + 1 - b)/y), 0)
The y is the length of an element of the dummy array. An assumed-size array can only be used as a whole array reference in the following cases: When it is an actual argument in a procedure reference that does not require the shape
5-15
Because the actual size of an assumed-size array is unknown, an assumed-size array cannot be used as any of the following in an I/O statement: An array name in the I/O list A unit identifier for an internal file A run-time format specifier The following is an example of an assumed-size specification:
SUBROUTINE SUB(A, N) REAL A, N DIMENSION A(1:N, *) ...
See Also
Array Elements for details on array element order
Deferred-Shape Specifications
A deferred-shape array is an array pointer or an allocatable array. The array specification contains a colon ( : ) for each dimension of the array. No bounds are specified. The bounds (and shape) of allocatable arrays and array pointers are determined when space is allocated for the array during program execution. An array pointer is an array declared with the POINTER attribute. Its bounds and shape are determined when it is associated with a target by pointer assignment, or when the pointer is allocated by execution of an ALLOCATE statement. In pointer assignment, the lower bound of each dimension of the array pointer is the result of the LBOUND intrinsic function applied to the corresponding dimension of the target. The upper bound of each dimension is the result of the UBOUND intrinsic function applied to the corresponding dimension of the target. A pointer dummy argument can be associated only with a pointer actual argument. An actual argument that is a pointer can be associated with a nonpointer dummy argument. A function result can be declared to have the pointer attribute. An allocatable array is declared with the ALLOCATABLE attribute. Its bounds and shape are determined when the array is allocated by execution of an ALLOCATE statement. The following are examples of deferred-shape specifications:
REAL, ALLOCATABLE :: A(:,:) REAL, POINTER :: C(:), D (:,:,:) ! Allocatable array ! Array pointers
5-16
Specification Statements
See Also POINTER Attribute and Statement ALLOCATABLE Attribute and Statement ALLOCATE Statement Pointer Assignments LBOUND UBOUND
5-17
An allocatable array cannot be specified in a COMMON, EQUIVALENCE, DATA, or NAMELIST statement. Allocatable arrays are not saved by default. If you want to retain the values of an allocatable array across procedure calls, you must specify the SAVE attribute for the array.
Examples
The following example shows a type declaration statement specifying the ALLOCATABLE attribute:
REAL, ALLOCATABLE :: Z(:, :, :)
See Also Type Declaration Statements ALLOCATE Statement DEALLOCATE Statement Allocation of Allocatable Arrays for details on allocation status Table 5-1 for details on compatible attributes
5-18
Specification Statements
A variable cannot be specified as AUTOMATIC or STATIC more than once in the same scoping unit.
5-19
If the variable is a pointer, AUTOMATIC or STATIC apply only to the pointer itself, not to any associated target. Some variables cannot be specified as AUTOMATIC or STATIC. The following table shows these restrictions:
Variable
Dummy argument Automatic object Common block item Use-associated item Function result Component of a derived type
AUTOMATIC
No No No No No No
STATIC
No No Yes No No No
A variable can be specified with both the STATIC and SAVE attributes. If a variable is in a modules outer scope, it can be specified as STATIC, but not as AUTOMATIC.
Examples
The following examples show type declaration statements specifying the AUTOMATIC and STATIC attributes:
REAL, AUTOMATIC :: A, B, C INTEGER, STATIC :: ARRAY_A
5-20
Specification Statements
SAVE Attribute and Statement Functions, Subroutines, and Statement Functions for details on subprograms Recursive Procedures for details on specifying recursive subprograms Table 5-1 for details on compatible attributes POINTER Attribute and Statement for details on pointers Modules and Module Procedures for details on modules Your users guide for details on compiler options
COMMON Statement
A COMMON statement defines one or more contiguous areas, or blocks, of physical storage (called common blocks) that can be accessed by any of the scoping units in an executable program. COMMON statements also define the order in which variables and arrays are stored in each common block, which can prevent misaligned data items. Common blocks can be named or unnamed (a blank common). The COMMON statement takes the following form: COMMON [/[cname]/] var-list [[,] /[cname]/ var-list]... cname Is the name of the common block. The name can be omitted for blank common (//). var-list Is a list of variable names, separated by commas. The variable must not be a dummy argument, allocatable array, automatic object, function, function result, or entry to a procedure. It must not have the PARAMETER attribute. If an object of derived type is specified, it must be a sequence type.
5-21
If an array is specified, it can be followed by an explicit-shape array specification, each bound of which must be a constant specification expression. Such an array must not have the POINTER attribute. A pointer can only be associated with pointers of the same type and kind parameters, and rank. An object with the TARGET attribute can only be associated with another object with the TARGET attribute and the same type and kind parameters. A nonpointer can only be associated with another nonpointer, but association depends on their types, as follows:
Type of Variable
Intrinsic numeric1 or numeric sequence2 Default character or character sequence2 Any other intrinsic type Any other sequence type
1. Default integer, default real, double precision real, default complex, double complex, or default logical. 2. If an object of numeric sequence or character sequence type appears in a common block, it is as if the individual components were enumerated directly in the common list.
So, variables can be associated if they are of different numeric type. For example, the following is valid:
INTEGER A(20) REAL Y(20) COMMON /QUANTA/ A, Y
When common blocks from different program units have the same name, they share the same storage area when the units are combined into an executable program. Entities are assigned storage in common blocks on a one-for-one basis. So, the data type of entities assigned by a COMMON statement in one program unit should agree with the data type of entities placed in a common block by another program unit. For example:
Program Unit A
COMMON CENTS ...
Program Unit B
INTEGER(2) MONEY COMMON MONEY ...
When these program units are combined into an executable program, incorrect results can occur if the 2-byte integer variable MONEY is made to correspond to the lower-addressed two bytes of the real variable CENTS.
5-22
Specification Statements
Named common blocks must be declared to have the same size in each program unit. Blank common can have different lengths in different program units. NOTE. If a common block is initialized by a DATA statement, the module containing the initialization must declare the common block to be its maximum defined length. This limitation does not apply if you compile all source modules together.
Examples
In the following example, the COMMON statement in the main program puts HEAT and X in blank common, and KILO and Q in a named common block, BLK1:
Main Program
COMMON HEAT, X /BLK1/KILO, Q ... CALL FIGURE ...
Subprogram
SUBROUTINE FIGURE COMMON /BLK1/LIMA, R / /ALFA,BET ... RETURN END
The COMMON statement in the subroutine makes ALFA and BET share the same storage location as HEAT and X in blank common. It makes LIMA and R share the same storage location as KILO and Q in BLK1. The following example shows how a COMMON statement can be used to declare arrays:
COMMON / MIXED / SPOTTED(100), STRIPED(50,50)
See Also Specification Expressions Storage Association Derived Data Types EQUIVALENCE Statement EQUIVALENCE and COMMON Interaction Your users guide for details on alignment of data items in common blocks
5-23
DATA Statement
The DATA statement assigns initial values to variables before program execution. It takes the following form: DATA var-list /c-list/[[,] var-list /c-list/]... var-list Is a list of variables or implied-DO lists, separated by commas. Subscript expressions and expressions in substring references must be initialization expressions. An implied-DO list in a DATA statement takes the following form: (do-list, var = expr1, expr2 [, expr3]) do-list Is a list of one or more array elements, substrings, scalar structure components, or implied-DO lists, separated by commas. Any array elements or scalar structure components must not have a constant parent. var Is the name of a scalar integer variable (the implied-DO variable). expr Are scalar integer expressions. The expressions can contain variables of other implied-DO lists that have this implied-DO list within their ranges. c-list Is a list of constants (or names of constants), or for pointer objects, NULL( ); constants must be separated by commas. If the constant is a structure constructor, each component must be an initialization expression. If the constant is in binary, octal, or hexadecimal form, the corresponding object must be of type integer. A constant can be specified in the form r*constant, where r is a repeat specification. It is a nonnegative scalar integer constant (with no kind parameter). If it is a named constant, it must have been declared previously in the scoping unit or made accessible through use or host association. If r is omitted, it is assumed to be 1.
5-24
Specification Statements
The following objects cannot be initialized in a DATA statement: A dummy argument A function A function result An automatic object An allocatable array A variable that is accessible by use or host association A variable in a named common block (unless the DATA statement is in a block data program unit) A variable in blank common Except for variables in named COMMON blocks, a named variable has the SAVE attribute if any part of it is initialized in a DATA statement. You can confirm this property by specifying the variable in a SAVE statement or a type declaration statement containing the SAVE attribute. When an unsubscripted array name appears in a DATA statement, values are assigned to every element of that array in the order of subscript progression. The associated constant list must contain enough values to fill the array. Array element values can be initialized in three ways: by name, by element, or by an implied-DO list (interpreted in the same way as a DO construct). The following conversion rules and restrictions apply to variable and constant list items: If the constant and the variable are both of numeric type, the following conversion occurs: The constant value is converted to the data type of the variable being initialized, if necessary. When a binary, octal, or hexadecimal constant is assigned to a variable or array element, the number of digits that can be assigned depends on the data type of the data item. If the constant contains fewer digits than the capacity of the variable or array element, the constant is extended on the left with zeros. If the constant contains more digits than can be stored, the constant is truncated on the left. If the constant and the variable are both of character type, the following conversion occurs: If the length of the constant is less than the length of the variable, the rightmost character positions of the variable are initialized with blank characters. If the length of the constant is greater than the length of the variable, the character constant is truncated on the right. If the constant is of numeric type and the variable is of character type, the following restrictions apply: The character variable must have a length of one character.
5-25
The constant must be an integer, binary, octal, or hexadecimal constant, and must have a value in the range 0 through 255. When the constant and variable conform to these restrictions, the variable is initialized with the character that has the ASCII code specified by the constant. (This lets you initialize a character object to any 8-bit ASCII code.) If the constant is a Hollerith or character constant, and the variable is a numeric variable or numeric array element, the number of characters that can be assigned depends on the data type of the data item. If the Hollerith or character constant contains fewer characters than the capacity of the variable or array element, the constant is extended on the right with blank characters. If the constant contains more characters than can be stored, the constant is truncated on the right.
Examples
The following example shows the three ways that DATA statements can initialize array element values:
DIMENSION A(10,10) DATA A/100*1.0/ ! initialization by name DATA A(1,1), A(10,1), A(3,3) /2*2.5, 2.0/ ! initialization by element DATA ((A(I,J), I=1,5,2), J=1,5) /15*1.0/ ! initialization by implied-DO list
In the following example, the first DATA statement assigns zero to all 10 elements of array A, and four asterisks followed by two blanks to the character variable STARS:
INTEGER A(10), B(10) CHARACTER BELL, TAB, LF, FF, STARS*6 DATA A,STARS /10*0,****/ DATA BELL,TAB,LF,FF /7,9,10,12/ DATA (B(I), I=1,10,2) /5*1/
In this case, the second DATA statement assigns ASCII control character codes to the character variables BELL, TAB, LF, and FF. The last DATA statement uses an implied-DO list to assign the value 1 to the odd-numbered elements in the array B.
5-26
Specification Statements
As a Fortran 95 feature, a pointer can be initialized as disassociated by using a DATA statement. For example:
INTEGER, POINTER :: P DATA P/NULL( )/ END
See Also Initialization and Specification Expressions Type Declaration Statements I/O Lists for details on implied-DO lists
5-27
The total number of storage elements assigned to an array is equal to the number produced by multiplying together the number of elements in each dimension in the array specification. For example, the following statement defines ARRAY as having 16 real elements of 4 bytes each and defines MATRIX as having 125 integer elements of 4 bytes each:
DIMENSION ARRAY(4,4), MATRIX(5,5,5)
An array can also be declared in the following statements: ALLOCATABLE, POINTER, TARGET, and COMMON.
Examples
The following examples show type declaration statements specifying the DIMENSION attribute:
REAL, DIMENSION(10, 10) :: A, B, C(10, 15) ! Specification following C ! overrides the one following ! DIMENSION
See Also Type Declaration Statements Arrays ALLOCATABLE Attribute and Statement COMMON Statement POINTER Attribute and Statement TARGET Attribute and Statement Declaration Statements for Arrays for details on array specifications Table 5-1 for details on compatible attributes
5-28
Specification Statements
EQUIVALENCE Statement
The EQUIVALENCE statement specifies that a storage area is shared by two or more objects in a program unit. This causes total or partial storage association of the objects that share the storage area. The EQUIVALENCE statement takes the following form: EQUIVALENCE (equiv-list) [, (equiv-list)]... equiv-list Is a list of two or more variables, array elements, or substrings, separated by commas (also called an equivalence set). If an object of derived type is specified, it must be a sequence type. Objects cannot have the TARGET attribute. Each expression in a subscript or a substring reference must be an integer initialization expression. A substring must not have a length of zero.
5-29
Type of Object
Any other sequence type
2. The lengths do not have to be equal.
1. Default integer, default real, double precision real, default complex, double complex, or default logical.
So, objects can be associated if they are of different numeric type. For example, the following is valid:
INTEGER A(20) REAL Y(20) EQUIVALENCE(A, Y)
Objects of default character do not need to have the same length. The following example associates character variable D with the last 4 (of the 6) characters of character array F:
CHARACTER(LEN=4) D CHARACTER(LEN=3) F(2) EQUIVALENCE(D, F(1)(3:))
Entities having different data types can be associated because multiple components of one data type can share storage with a single component of a higher-ranked data type. For example, if you make an integer variable equivalent to a complex variable, the integer variable shares storage with the real part of the complex variable. The same storage unit cannot occur more than once in a storage sequence, and consecutive storage units cannot be specified in a way that would make them nonconsecutive.
Examples
The following EQUIVALENCE statement is invalid because it specifies the same storage unit for X(1) and X(2):
REAL, DIMENSION(2), :: X REAL :: Y EQUIVALENCE(X(1), Y), (X(2), Y)
The following EQUIVALENCE statement is invalid because A(1) and A(2) will not be consecutive:
REAL A(2) DOUBLE PRECISION D(2) EQUIVALENCE(A(1), D(1)), (A(2), D(2))
In the following example, the EQUIVALENCE statement causes the four elements of the integer array IARR to share the same storage as that of the double-precision variable DVAR.
DOUBLE PRECISION DVAR
5-30
Specification Statements
In the following example, the EQUIVALENCE statement causes the first character of the character variables KEY and STAR to share the same storage location. The character variable STAR is equivalent to the substring KEY(1:10).
CHARACTER KEY*16, STAR*10 EQUIVALENCE(KEY, STAR)
See Also Initialization Expressions Derived Data Types Storage Association for details on storage units, sequence, and association
These statements cause the entire array TABLE to share part of the storage allocated to TRIPLE. Table 5-3 shows how these statements align the arrays:
Table 5-3 Array TRIPLE Array Elements
TRIPLE(1,1,1) TRIPLE(2,1,1) TRIPLE(1,2,1)
Array Element
Element Number
5-31
Array Elements
TRIPLE(2,2,1) TRIPLE(1,1,2) TRIPLE(2,1,2) TRIPLE(1,2,2) TRIPLE(2,2,2)
Array Element
TABLE(1,1) TABLE(2,1) TABLE(1,2) TABLE(2,2)
Element Number
1 2 3 4
Each of the following statements also aligns the two arrays as shown in Table 5-3:
EQUIVALENCE(TABLE, TRIPLE(2,2,1)) EQUIVALENCE(TRIPLE(1,1,2), TABLE(2,1))
You can also make arrays equivalent with nonunity lower bounds. For example, an array defined as A(2:3,4) is a sequence of eight values. A reference to A(2,2) refers to the third element in the sequence. To make array A(2:3,4) share storage with array B(2:4,4), you can use the following statement:
EQUIVALENCE(A(3,4), B(2,4))
The entire array A shares part of the storage allocated to array B. Table 5-4 shows how these statements align the arrays. The arrays can also be aligned by the following statements:
EQUIVALENCE(A, B(4,1)) EQUIVALENCE(B(3,2), A(2,2))
Array Element
B(2,1) B(3,1) B(4,1) B(2,2) B(3,2) B(4,2) B(2,3) B(3,3) B(4,3) B(2,4) B(3,4)
Array Element
Element Number
5-32
Specification Statements
Array Element
B(4,4)
Array Element
Element Number
Only in the EQUIVALENCE statement can you identify an array element with a single subscript (the linear element number), even though the array was defined as multidimensional. For example, the following statements align the two arrays as shown in Table 5-4:
DIMENSION B(2:4,1:4), A(2:3,1:4) EQUIVALENCE(B(6), A(4))
These statements cause character variables NAME and ID to share space (see Figure 5-1). The arrays can also be aligned by the following statement:
EQUIVALENCE(NAME(9:9), ID(1:1))
5-33
Figure 5-1
Equivalence of Substrings
If the character substring references are array elements, the EQUIVALENCE statement sets associations between the other corresponding characters in the complete arrays. Character elements of arrays can overlap at any character position. For example, the following statements cause character arrays FIELDS and STAR to share storage (see Figure 5-2).
5-34
Specification Statements
The EQUIVALENCE statement cannot assign the same storage location to two or more substrings that start at different character positions in the same character variable or character array. The EQUIVALENCE statement also cannot assign memory locations in a way that is inconsistent with the normal linear storage of character variables and arrays.
Examples
Figure 5-3 and Figure 5-4 show valid and invalid extensions of the common block, respectively.
5-35
Figure 5-2
100
1 2 3 4 ZK0619GE
5-36
Specification Statements
Figure 5-3
Valid DIMENSION A (4), B (6) COMMON A EQUIVALENCE (A (2), B (1)) A (1) A (2) A (3) A (4) B (1) B (2) B (3) B (4) B (5) B (6) Existing Common Extended Portion ZK1944GE
Figure 5-4
Invalid DIMENSION A (4), B (6) COMMON A EQUIVALENCE (A (2), B (3)) A (1) A (2) A (3) A (4) B (1) B (2) B (3) B (4) B (5) B (6) Extended Portion Existing Common Extended Portion ZK1945GE
The second example is invalid because the extended portion, B(1), precedes the first element of the common block. The following example shows a valid EQUIVALENCE statement and an invalid EQUIVALENCE statement in the context of a common block.
COMMON A, B, C DIMENSION D(3) EQUIVALENCE(B, D(1))
5-37
5-38
Specification Statements
Examples
The following example shows type declaration statements specifying the EXTERNAL attribute:
PROGRAM TEST ... INTEGER, EXTERNAL :: BETA LOGICAL, EXTERNAL :: COS ... CALL SUB(BETA) ! External function BETA is an actual argument
You can use a name specified in an EXTERNAL statement as an actual argument to a subprogram, and the subprogram can then use the corresponding dummy argument in a function reference or a CALL statement; for example:
EXTERNAL FACET CALL BAR(FACET) SUBROUTINE BAR(F) EXTERNAL F CALL F(2)
Used as an argument, a complete function reference represents a value, not a subprogram; for example, FUNC(B) represents a value in the following statement:
CALL SUBR(A, FUNC(B), C)
See Also Type Declaration Statements Chapter 9, Intrinsic Procedures INTRINSIC Attribute and Statement Table 5-1 for details on compatible attributes
IMPLICIT Statement
The IMPLICIT statement overrides the default implicit typing rules for names. (The default data type is INTEGER for names beginning with the letters I through N, and REAL for names beginning with any other letter.) The IMPLICIT statement takes one of the following forms: IMPLICIT type (a[, a]...)[, type (a[, a]...)]... IMPLICIT NONE
5-39
type Is a data type specifier (CHARACTER*(*) is not allowed). a Is a single letter, a dollar sign ($), or a range of letters in alphabetical order. The form for a range of letters is a1-a2, where the second letter follows the first alphabetically (for example, A-C). The dollar sign can be used at the end of a range of letters, since IMPLICIT interprets the dollar sign to alphabetically follow the letter Z. For example, a range of X$ would apply to identifiers beginning with the letters X, Y, Z, or $.
The following IMPLICIT statement represents the default typing for names when they are not explicitly typed:
IMPLICIT INTEGER (I-N), REAL (A-H, O-Z)
Examples
The following are examples of the IMPLICIT statement:
IMPLICIT IMPLICIT IMPLICIT IMPLICIT DOUBLE PRECISION (D) COMPLEX (S,Y), LOGICAL(1) (L,A-C) CHARACTER*32 (T-V) CHARACTER*2 (W)
5-40
Specification Statements
See Also
Your users guide for details on compiler options
5-41
d-arg Is the name of a dummy argument. It cannot be a dummy procedure or dummy pointer.
Examples
The following example shows type declaration statements specifying the INTENT attribute:
SUBROUTINE TEST(I, J) INTEGER, INTENT(IN) :: I INTEGER, INTENT(OUT), DIMENSION(I) :: J
5-42
Specification Statements
INTENT(INOUT) :: A, B ... SUBROUTINE CHANGE(FROM, TO) USE EMPLOYEE_MODULE TYPE(EMPLOYEE) FROM, TO INTENT(IN) FROM INTENT(OUT) TO ...
See Also Type Declaration Statements Argument Association Table 5-1 for details on compatible attributes
5-43
The name declared INTRINSIC is assumed to be the name of an intrinsic procedure. If a generic intrinsic function name is given the INTRINSIC attribute, the name retains its generic properties.
Examples
The following example shows a type declaration statement specifying the INTRINSIC attribute:
PROGRAM EXAMPLE ... REAL(8), INTRINSIC :: DACOS ... CALL TEST(X, DACOS) ! Intrinsic function DACOS is an actual argument
Subprogram
SUBROUTINE TRIG(X,F,Y) Y = F(X) RETURN END
Note that when TRIG is called with a second argument of SIN or COS, the function reference F(X) references the Fortran 95/90 library functions SIN and COS; but when TRIG is called with a second argument of CTN, F(X) references the user function CTN.
See Also Type Declaration Statements References to Generic Intrinsic Functions References to Elemental Intrinsic Procedures Chapter 9, Intrinsic Procedures, for details on specific intrinsic procedures Table 5-1 for details on compatible attributes
5-44
Specification Statements
NAMELIST Statement
The NAMELIST statement associates a name with a list of variables. This group name can be referenced in some input/output operations. A NAMELIST statement takes the following form: NAMELIST /group/var-list [[,] /group/var-list]... group Is the name of the group. var-list Is a list of variables (separated by commas) that are to be associated with the preceding group name. The variables can be of any data type.
5-45
The group name can be specified in more than one NAMELIST statement in a scoping unit. The variable list following each successive appearance of the group name is treated as a continuation of the list for that group name.
Examples
In the following example, D and E are added to the variables A, B, and C for group name LIST:
NAMELIST /LIST/ A, B, C NAMELIST /LIST/ D, E
Group name INPUT contains variables NAME, GRADE, and DATE. Group name OUTPUT contains variables TOTAL and NAME.
See Also Rules for Namelist Sequential READ Statements for details on namelist input Rules for Namelist Sequential WRITE Statements for details on namelist output
5-46
Specification Statements
Examples
The following example shows a type declaration statement specifying the OPTIONAL attribute:
SUBROUTINE TEST(A) REAL, OPTIONAL, DIMENSION(-10:2) :: A END SUBROUTINE
5-47
Note that in the second call to subroutine TEST, the second positional (optional) argument is omitted. In this case, all following arguments must be keyword arguments.
See Also Type Declaration Statements PRESENT Optional Arguments Table 5-1 for details on compatible attributes
5-48
Specification Statements
According to implicit typing, MU is of integer type, so MU=1. For MU to equal 1.23, it should previously be declared REAL in a type declaration or be declared in an IMPLICIT statement. A named constant must not appear in a format specification or as the character count for Hollerith constants. For compilation purposes, writing the name is the same as writing the value. If the named constant is used as the length specifier in a CHARACTER declaration, it must be enclosed in parentheses. The name of a constant cannot appear as part of another constant, although it can appear as either the real or imaginary part of a complex constant. You can only use the named constant within the scoping unit containing the defining PARAMETER statement. Any named constant that appears in the initialization expression must have been defined previously in the same type declaration statement (or in a previous type declaration statement or PARAMETER statement), or made accessible by use or host association.
Examples
The following example shows a type declaration statement specifying the PARAMETER attribute:
REAL, PARAMETER :: C = 2.9979251, Y = (4.1 / 3.0)
See Also Type Declaration Statements Initialization Expressions IMPLICIT Statement Alternative Syntax for the PARAMETER Statement Table 5-1 for details on compatible attributes
5-49
5-50
Specification Statements
Examples
The following example shows type declaration statements specifying the POINTER attribute:
TYPE(SYSTEM), POINTER :: CURRENT, LAST REAL, DIMENSION(:,:), POINTER :: I, J, REVERSE
See Also Type Declaration Statements Pointer Assignments ALLOCATE Statement Pointer Association Pointer Arguments ASSOCIATED Deferred-Shape Specifications for details on deferred-shape arrays NULL, which can be used to disassociate a pointer Table 5-1 for details on compatible attributes
5-51
entity Is one of the following: A variable name A procedure name A derived type name A named constant A namelist group name In statement form, an entity can also be a generic identifier (a generic name, defined operator, or defined assignment).
Examples
The following examples show type declaration statements specifying the PUBLIC and PRIVATE attributes:
REAL, PRIVATE :: A, B, C INTEGER, PUBLIC :: LOCAL_SUMS
5-52
Specification Statements
MODULE SOME_DATA REAL ALL_B PUBLIC ALL_B TYPE RESTRICTED_DATA REAL LOCAL_C DIMENSION LOCAL_C(50) END TYPE RESTRICTED_DATA PRIVATE RESTRICTED_DATA END MODULE
The following derived-type declaration statement indicates that the type is restricted to the module:
TYPE, PRIVATE ... END TYPE DATA :: DATA
In this case, components C and D are private to type ELEMENTS, but type ELEMENTS is not private to MODULE MATTER. Any program unit that uses the module MATTER, can declare variables of type ELEMENTS, and pass as arguments values of type ELEMENTS.
See Also Type Declaration Statements Derived Data Types USE Statement Use and Host Association Defining Generic Names for Procedures for details on generic identifiers Modules and Module Procedures for details on modules Table 5-1 for details on compatible attributes
5-53
5-54
Specification Statements
When a SAVE statement does not explicitly contain a list, all allowable items in the scoping unit are saved. A SAVE statement cannot specify the following (their values cannot be saved): A blank common An object in a common block A procedure A dummy argument A function result An automatic object A PARAMETER (named) constant Even though a common block can be included in a SAVE statement, individual variables within the common block can become undefined (or redefined) in another scoping unit. If a common block is saved in any scoping unit of a program (other than the main program), it must be saved in every scoping unit in which the common block appears. A SAVE statement has no effect in a main program.
Examples
The following example shows a type declaration statement specifying the SAVE attribute:
SUBROUTINE TEST() REAL, SAVE :: X, Y
See Also Type Declaration Statements DATA Statement COMMON Statement for details on common blocks Recursive Procedures for details on recursive program units Modules and Module Procedures for details on modules. Table 5-1 for details on compatible attributes
5-55
The TARGET attribute can be specified in a type declaration statement or a TARGET statement, and takes one of the following forms: Type Declaration Statement: type, [att-ls,] TARGET [, att-ls] :: object [(a-spec)] [, object [(a-spec)]]... Statement: TARGET [::] object [(a-spec)] [, object [(a-spec)]]... type Is a data type specifier. att-ls Is an optional list of attribute specifiers. object Is the name of the object. The object must not be declared with the PARAMETER attribute. a-spec Is an array specification.
Examples
The following example shows type declaration statements specifying the TARGET attribute:
TYPE(SYSTEM), TARGET :: FIRST REAL, DIMENSION(20, 20), TARGET :: C, D
See Also Type Declaration Statements ALLOCATE Statement Pointer Assignments Pointer Association Table 5-1 for details on compatible attributes
5-56
Specification Statements
5-57
Examples
The following example shows a type declaration statement specifying the VOLATILE attribute:
INTEGER, VOLATILE :: D, E
The named common block, BLK1, and the variables D and E are volatile. Variables P1 and P4 become volatile because of the direct equivalence of P1 and the indirect equivalence of P4.
See Also Type Declaration Statements Table 5-1 for details on compatible attributes Your users guide for details on optimizations performed by the compiler
5-58
Dynamic Allocation
Data objects can be static or dynamic. If a data object is static, a fixed amount of memory storage is created for it at compile time and is not freed until the program exits. If a data object is dynamic, memory storage for the object can be created (allocated), altered, or freed (deallocated) as a program executes. In Fortran 95/90, pointers, allocatable arrays, and automatic arrays are dynamic data objects. No storage space is created for a pointer until it is allocated with an ALLOCATE statement or until it is assigned to a allocated target. A pointer can be dynamically disassociated from a target by using a NULLIFY statement. An ALLOCATE statement can also be used to create storage for an allocatable array. A DEALLOCATE statement is used to free the storage space reserved in a previous ALLOCATE statement. Automatic arrays differ from allocatable arrays in that they are automatically allocated and deallocated whenever you enter or leave a procedure, respectively.
This chapter contains information on the following topics: The ALLOCATE Statement The DEALLOCATE Statement The NULLIFY Statement
See Also Pointer Assignments Explicit-Shape Specifications for details on automatic arrays NULL, which can also be used to disassociate a pointer
6-1
ALLOCATE Statement
The ALLOCATE statement dynamically creates storage for allocatable arrays and pointer targets. The storage space allocated is uninitialized. The ALLOCATE statement takes the following form: ALLOCATE (object [(s-spec[, s-spec...])] [, object[(s-spec[, s-spec...])]]...[, STAT=sv]) object Is the object to be allocated. It is a variable name or structure component, and must be a pointer or allocatable array. The object can be of type character with zero length. s-spec Is a shape specification in the form [lower-bound:]upper-bound. Each bound must be a scalar integer expression. The number of shape specifications must be the same as the rank of the object. sv Is a scalar integer variable in which the status of the allocation is stored.
If a STAT variable is specified, it must not be allocated in the ALLOCATE statement in which it appears. If the allocation is successful, the variable is set to zero. If the allocation is not successful, an error condition occurs, and the variable is set to a positive integer value (representing the run-time error). If no STAT variable is specified and an error condition occurs, program execution terminates.
Examples
The following is an example of the ALLOCATE statement:
INTEGER J, N, ALLOC_ERR REAL, ALLOCATABLE :: A(:), B(:,:) ... ALLOCATE(A(0:80), B(-3:J+1, N), STAT = ALLOC_ERR)
6-2
Dynamic Allocation
See Also ALLOCATABLE Attribute and Statement for details on allocatable arrays POINTER Attribute and Statement for details on pointers Your users guide or online documentation for details on run-time error messages
Allocation Status
During program execution, the allocation status of an allocatable array is one of the following: Not currently allocated The array was never allocated or the last operation on it was a deallocation. Such an array must not be referenced or defined. Currently allocated The array was allocated by an ALLOCATE statement. Such an array can be referenced, defined, or deallocated. If an allocatable array has the SAVE attribute, it has an initial status of "not currently allocated". If the array is then allocated, its status changes to "currently allocated". It keeps that status until the array is deallocated. If an allocatable array does not have the SAVE attribute, it has the status of "not currently allocated" at the beginning of each invocation of the procedure. If the arrays status changes to "currently allocated", it is deallocated if the procedure is terminated by execution of a RETURN or END statement.
6-3
Examples
Example 6-1 shows a program that performs virtual memory allocation. This program uses Fortran 95/90 standard-conforming statements instead of calling an operating system memory allocation routine.
Example 6-1 Allocating Virtual Memory
! Program accepts an integer and displays square root values INTEGER(4) :: N READ (5,*) N CALL MAT(N) END
! Subroutine MAT uses the typed integer value to display the square ! root values of numbers from 1 to N (the number read) SUBROUTINE MAT(N) REAL(4), ALLOCATABLE :: SQR(:) ALLOCATE (SQR(N)) DO J=1,N SQR(J) = SQRT(FLOATJ(J)) ENDDO WRITE (6,*) SQR DEALLOCATE (SQR) END SUBROUTINE MAT
! Declares SQR as a one-dimensional ! allocatable array ! Allocates array SQR ! FLOATJ converts integer to REAL
See Also
ALLOCATED
6-4
Dynamic Allocation
In contrast to allocatable arrays, a pointer can be allocated a new target even if it is currently associated with a target. The previous association is broken and the pointer is then associated with the new target. If the previous target was created by allocation, it becomes inaccessible unless it can still be referred to by other pointers that are currently associated with it. The intrinsic function ASSOCIATED can be used to determine whether a pointer is currently associated with a target. (The association status of the pointer must be defined.) For example:
REAL, TARGET :: TAR(0:50) REAL, POINTER :: PTR(:) PTR => TAR ... IF (ASSOCIATED(PTR,TAR))...
See Also Pointer Assignments ASSOCIATED POINTER Attribute and Statement for details on pointers
DEALLOCATE Statement
The DEALLOCATE statement frees the storage allocated for allocatable arrays and pointer targets (and causes the pointers to become disassociated). It takes the following form: DEALLOCATE (object [, object]...[, STAT=sv]) object Is a structure component or the name of a variable, and must be a pointer or allocatable array. sv Is a scalar integer variable in which the status of the deallocation is stored.
6-5
Examples
The following example shows deallocation of an allocatable array:
INTEGER ALLOC_ERR REAL, ALLOCATABLE :: A(:), B(:,:) ... ALLOCATE (A(10), B(-2:8,1:5)) ... DEALLOCATE(A, B, STAT = ALLOC_ERR)
See Also
Your users guide or online documentation for details on run-time error messages
6-6
Dynamic Allocation
Note that when subroutine TEST is exited, the allocation status of F is maintained because F has the SAVE attribute. Since E does not have the SAVE attribute, it is deallocated. On the next invocation of TEST, E will have the status of "not currently allocated".
See Also Use and Host Association TARGET Attribute and Statement RETURN Statement END Statement SAVE Attribute and Statement
Examples
The following example shows deallocation of a pointer:
6-7
INTEGER ERR REAL, POINTER :: PTR_A(:) ... ALLOCATE (PTR_A(10), STAT=ERR) ... DEALLOCATE(PTR_A)
See Also Use and Host Association RETURN Statement END Statement SAVE Attribute and Statement POINTER Attribute and Statement for details on pointers COMMON Statement for details on common blocks NULL, which can be used to disassociate a pointer
NULLIFY Statement
The NULLIFY statement disassociates a pointer from its target. It takes the following form: NULLIFY (pointer-object [, pointer-object]...) pointer-object Is a structure component or the name of a variable; it must be a pointer (have the POINTER attribute).
Examples
The following is an example of the NULLIFY statement:
REAL, TARGET :: TAR(0:50) REAL, POINTER :: PTR_A(:), PTR_B(:) PTR_A => TAR PTR_B => TAR ... NULLIFY(PTR_A)
6-8
Dynamic Allocation
After these statements are executed, PTR_A will have disassociated status, while PTR_B will continue to be associated with variable TAR.
See Also POINTER Attribute and Statement Pointer Assignments ASSOCIATED NULL, which can be used to disassociate a pointer
6-9
6-10
Execution Control
A program normally executes statements in the order in which they are written. Executable control constructs and statements modify this normal execution by transferring control to another statement in the program, or by selecting blocks (groups) of constructs and statements for execution or repetition. In Fortran 95/90, control constructs (CASE, DO, and IF) can be named. The name must be a unique identifier in the scoping unit, and must appear on the initial line and terminal line of the construct. On the initial line, the name is separated from the statement keyword by a colon (:). A block can contain any executable Fortran statement except an END statement. You can transfer control out of a block, but you cannot transfer control into another block. DO loops cannot partially overlap blocks. The DO statement and its terminal statement must appear together in a statement block. This chapter contains information on the following topics: The Branch Statements The CALL Statement The CASE Constructs The CONTINUE Statement The DO Constructs The END Statement The IF Construct and Statement The PAUSE Statement The RETURN Statement The STOP Statement
7-1
Branch Statements
Branching affects the normal execution sequence by transferring control to a labeled statement in the same scoping unit. The transfer statement is called the branch statement, while the statement to which the transfer is made is called the branch target statement. Any executable statement can be a branch target statement, except for the following: CASE statement ELSE statement ELSE IF statement Certain restrictions apply to the following statements:
Statement
DO terminal statement END DO END IF END SELECT
Restriction
The branch must be taken from within its nonblock DO construct.1 The branch must be taken from within its block DO construct. The branch should be taken from within its IF construct.2 The branch must be taken from within its CASE construct.
1. If the terminal statement is shared by more than one nonblock DO construct, the branch can only be taken from within the innermost DO construct. 2. You can branch to an END IF statement from outside the IF construct; this is a deleted feature in Fortran 95. Intel Fortran fully supports features deleted in Fortran 95.
The following branch statements are described in this section: Unconditional GO TO Statement Computed GO TO Statement The ASSIGN and Assigned GO TO Statements Arithmetic IF Statement
Unconditional GO TO Statement
The unconditional GO TO statement transfers control to the same branch target statement every time it executes. It takes the following form: GO TO label
7-2
Execution Control
label Is the label of a valid branch target statement in the same scoping unit as the GO TO statement. The unconditional GO TO statement transfers control to the branch target statement identified by the specified label. The following are examples of GO TO statements:
GO TO 7734 GO TO 99999
Computed GO TO Statement
The computed GO TO statement transfers control to one of a set of labeled branch target statements based on the value of an expression. It is an obsolescent feature in Fortran 95. The computed GO TO statement takes the following form: GO TO (label-list)[,] expr label-list Is a list of labels (separated by commas) of valid branch target statements in the same scoping unit as the computed GO TO statement. (Also called the transfer list.) The same label can appear more than once in this list. expr Is a scalar numeric expression in the range 1 to n, where n is the number of statement labels in label-list. If necessary, it is converted to integer data type.