SVS_Fortran_CPM_68K_Sep83 SVS Fortran CPM 68K Sep83
SVS_Fortran_CPM_68K_Sep83 SVS_Fortran_CPM_68K_Sep83
User Manual: SVS_Fortran_CPM_68K_Sep83
Open the PDF directly: View PDF .
Page Count: 192
Download | |
Open PDF In Browser | View PDF |
Fortran Reference Manual SIlicon Valley Software, Inc. 10011 N. FoothIll Blvd .. Suite III CupertIno. CA 95014 FORTRAN Language Reference Manual Version 2.0 of 1st September 1983 Silicon Valley Software, Inc. 10011 North Foothill Blvd. Suite 111 Cupertino California 95014 This PORTRAN Reference Manual was produced by: Jeffrey Barth, R. Steven Glanville, and Henry McGilton. Silicon Valley Software, Inc. Publication Number: 810715-02 Copyright 1983 by Silicon Valley Software, Inc. All rights reserved. No part of this PORTRAN Reference Manual may be reproduced, translated, transcribed or transmitted in any form or by any means manual, electronic, electro-magnetic, chemicalor optical without explicit written permission from Silicon valley Software, Inc. Preface PREFACE This manual is a reference manual for SVS FORTRAN-77 an implementation of the full ANSI FORTRAN-77 computer programming language for Motorola MC68000 computer systems. FORTRAN is one of the most widely used programming languages to date. FORTRAN is primarily oriented towards scientific computing applications. FORTRAN's evolution has developed from its early beginnings as FORTRAN-II through to FORTRAN-IV, for which an ANSI standard was adopted in 1966. By the middle of the 1970's decade, it was apparent that many of the most widely used extensions to FORTRAN-IV could form the basis for a new FORTRAN language standard. Atl updated language (called FORTRAN-77 by consensus) was announced in 1977. The formal standard was issued by the American National Standards Institute (ANSI) in 1978. The ANSI standard for FORTRAN-77 actually defines two languages: a "full" language and a "subset" language. The subset omits certain items such as the complex data-type and listdirected input-output. SVS FORTRAN implements the full language. SCOPE OF THIS MANUAL This is a reference manual, as opposed to a "how to write FORTRAN programs" manual. There are several tutorial-style FORTRAN books on the market for novice FORTRAN users. OVERVIEW OF THIS MANUAL Chapter 1 - "Introduction" is a general overview of FORTRAN. Terms and concepts of FORTRAN are introduced here, as is the metalanguage that this manual uses to describe FORTRAN. Preface Chapter 2 - "Lines, Statements, and Control Flow" introduces the ideas of lines, statements and execution seguence. Chapter 3 - "Data Types and Constants" introduces FORTRAN and constants. data ~ Chapter 4 - "FORTRAN Names, Arrays, and FORTRAN ~, arrays and substrings. Substrings" discusses Chapter 5 - "Expression" describes the rules for expressions in FORTRAN. Chapter 6 - "Specification Statements" is a description of specification statements used to declare data variables and their attributes. Chapter 7 - "Data Initialization" discusses data initialization, that is, static data initialization via DATA statements. Chapter 8 - "Assignment Statements" describes assignment statewhereby variables are assigned new values. ~ Chapter 9 - "Control Statements" presents that direct the flow of program execution. control statements Chapter 10 "FORTRAN Input Output" covers input outputstatements which are the means whereby a program communicates with the world external to the computer. Chapter 11 - "Format Specifications" is about format statements which describe the conversion process between internal data representations and external formats. Chapter 12 - "Program and Subprogram Structure" describes P1 9and sUbProaram structure where~y large programs can be sp lt lnto smaller an more manageable unlts. ~ram Chapter 13 - "FORTRAN Compile Time Options" describes the piler options which control the actions of the compiler. com- Appendix A is a list of FORTRAN error messages. Appendix B contains a table of FORTRAN intrinsic functions the "built-inn functions for performing mathematical computations. Appendix C describes FORTRAN's data representation methods parameter passing mechanism. and Appendix D is an ASCII character set chart. Appendix E - "Operating the SVS FORTRAN System" describeS the system independent aspects of operating the system and the Preface considerations involved in linking programs languages. written in several Appendix F - ·Operating System Specific Information" contains a description of how to run the FORTRAN compiler on the host operating· system, and also covers details of specific dependencies and interfacing requirements (if any) of the host operating system. CONTENTS Chapter 1 - Introduction..................................... 1.1 Overview of the FORTRAN Language........................ 1.2 Notation and Terminology Used in this Manual............ 1.3 Basic Elements of FORTRAN............................... 1.3.1 FORTRAN Character Set............................ 1.3.2 Collating Sequence and Graphics.................. 1.3.3 Use of Spaces or Blanks or Tabs.................. 1 1 4 5 5 6 6 Chapter 2 - Lines, State.ents, and Control Plow.............. 2.1 Lines................................................... 2.1.1 Comment Lines.................................... 2.1.2 Initial Lines •••••••••••••••••••••••••••••••••••• 2.1.3 Continuation Lines ••••••••••••••••••••••••••••••• 2.1.4 Compiler Directive Lines ••••••••••••••••••••••••• 2.2 Statements •••••••••••••••••••••••••••••••••••••••••••••• 2.2.1 Statement Labels ••••••••••••••••••••••••••••••••• 2.2.2 Order of Statements and Lines •••••••••••••••••••• . 2.3 Execution Sequence and Control Transfer ••••••••••••••••• 9 9 9 10 10 11 11 12 13 14 Chapter 3 - Data Types and Constants ••••••••••••••••••••••••• 3.1 Data Type Rules ••••••••••••••••••••••••••••••••••••••••• 3.2 Constants ••••••••••••••••••••••••••••••••••••••••••••••• 3.3 Integer Data Type ••••••••••••••••••••••••••••••••••••••• 3.4 Real Data Type •••••••••••••••••••••••••••••••••••••••••• 3.4.1 Infinite and Indeterminate Real Values........... 3.5 Double Precision Data Type ••••••••.•••••••••••••••••• ~. 3.6 Complex Data Type....................................... 3.7 Character Data.Type ••.••••••••••••••••••••••••••••.••••• 3.8 Logical Data Type ••••••••••••••••••••••••••••••••••••••• 17 17 17 18 19 20 20 20 21 22 Chapter 4 - PORTRAN Names, Arrays, and Substrings •••••••••••• 4.1 FORTRAN Names •••••••••••••••••••••••••••• ~ • • • • • • • • • • • • • • 4.1.1 Scope of FORTRAN Names........................... 4.1.2 Undeclared FORTRAN Names •••.••••••••••••.•••••••• 4.2 Array Declarations ••••••••••.••••••••••••••••••••••••••• 4.2.1 Dimension Declarations •••••••••••.•••••.••••••••• 4.2.2 Kinds of Array Declarations •••••••••••••••••••••• 4.2.3 Actual Arrays and Dummy Arrays ••••••••••••••••••• 4.2.4 Referencing Array Elements - Array Subscr ipts. • • • • • • • • • • • • • • • • • • • • . • • • • • • • • • • • .• • • • • • • . 4.2.5 Using Unsubscripted Array Names ••••••••.••••••.•• 4.3 Character Substrings •••.••••.••••••.•••••••••••.•••••••• 23 23 24 25 25 26 26 27 Chapter 5 - Expressions ...•••••••••••••••..•.•••••...••••••.• 5.1 Arithmetic Expressions ••••••••••••••••••••••••••••••••.• 5.1.1 Arithmetic Operators ••••••••••••••••••.••••••••• 5.1.2 Arithmetic Operands •••.•.•••.•••.•.•••...••••••.• 5.1.3 Constant Expressions •...•••••.••••••••••.••••••.• 5.1.4 Type Conversion Rules for Arithmetic Expressions ••••••••••••••••••••••••••••••••••••••••••.• 31 31 31 32 33 - i - 27 28 29 33 Rules for Add, Subtract, Multiply and Di vide. • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • 5.1.4.2 Rules for Exponentiation Operator....... Coercion Rules for Integers of Different 5.1.4.1 5.1.5 34 34 Size............................................. 35 Integer Division ••••••••••••••••••••••••••••••••• Character Expressions ••••••••••••••••••••••••••••••••••• 5.2.1 Restrictions on the use of String Expressions. • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • Relational Expressions •••..•••••••••••.•.••..•.••••••••• 5.3.1 Arithmetic Relational Expressions •••••••••••••••• 5.3.2 Character Relational Expressions ••••••••••••••••• Logical Expressions ••••••••••••••••••••••••••••••••••••• 5.4.1 Precedence of Logical Operators.................. Precedence of Operators................................. Evaluation Rules and Restrictions for Expressions ••••••• 5.6.1 Restrictions on Function References •••••••••••••• 36 36 36 37 37 37 38 38 39 39 40 Chapter 6 - Specification Statements ••••••••••••••••••••••••• 6.1 Type Statements - Declaring Data Types •••••••••••••••••• 6.1.1 Arithmetic Type Statements ••••••••••••••••••••••• 6.1.2 CHARACTER Type Statement ••••••••••••••••••••••••• 6.1.3 LOGICAL Type Statement •••••••••••••••••.•••••••.•• 6.2 DIMENSION - Declare Data Dimension •••••••••••••••••••••• 6.2.1 Dimension Declarators •••••••••••••••••••••••••••• 6.3 COMMON - Declare a COMMON Block ••••••••••••••••••••••••• 6.4 PARAMETER - Make a Symbolic Association ••••••••••••••••• 6.5 IMPLICIT - Establish Default Data Type •••••••••••••••••• 6.6 EXTERNAL - Declare External or Dummy Procedure •••••••••• 6.7 INTRINSIC - Declare Intrinsic Function •••••••••••••••••• 6.8 SAVE - Retain Definition Status ••••••••••••••••••••••••• 6.9 EQUIVALENCE - Share Storage Between Elements •••••••••••• 6.9.1 Restrictions on EQUIVALENCE Statements ••••••••••• 41 41 42 42 43 44 44 44 45 46 47 47 48 49 50 Chapter 7 - Data Initialization •••••••••••••••••••••••.•••••• 7.1 Initializing Character Variables •••••••••••••••••••••••• 7.2 Initializing Non CHARACTER Variables to CHARACTER Values. • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • 7.3 Implied DO in DATA Statements........................... 51 52 Chapter 8 - Assignment Statements •••••••••••••••••••••••••••• 8.1 Arithmetic Assignment •••• ~ •••••••••••••••••••••••••••••• 8.2 Logical Assignment...................................... 8.3 Statement Label Assignment ••••••••••••••••••••••••• ~ •••• 8.4 Character Assignment •••••.••..••••••••••••.••••••••••••• 57 57 58 59 60 Chapter 9 - Control Statements.............................. 9.1 Block IF THEN ELSE Statement......................... 9.1.1 Block IF Statement........................... 9.1.2 ELSEIF Statement............................. 9.1.3 ELSE Statement............................... 9.1.4 ENDIF Statement.............................. 61 62 63 64 64 65 5.1.6 5.2 5.3 5.4 5.5 5.6 - ii - 53 54 9.2 9.3 9.4 9.5 9.6 9.7 9.8 9.9 9.10 Logical IF Statement ••••••••••••••••••••••••••••••••• Arithmetic IF Statement ••••.••••••••••••••••••••••••• DO Statement - Loop Control •••••••••••••••••••••••••• 9.4.1 DO Loop Initialization Sequence •••••••••••••• 9.4.2 DO Loop Incrementation Processing •••••••••••• 9.4.3 Events Which Terminate a DO Loop ••••••••••••• CONTINUE Statement - Null Statement •••••••••••••••••• STOP Statement - Stop Program Execution •••••••.•••••• PAUSE Statement - Suspend Program Execution •••••••••• Unconditional GO TO Statement •••••••••••••••••••••••• Computed GO TO Statement ••••••••••••••••••••••••••••• Assigned GO TO Statement ••••••••••••••••••••••••••••• Chapter 10 - Input and Output ••••••••••••••••••••••••••••••• 10.1 Overview of the Input-Output System.................. 10.1.1 Records...................................... 10.1.2 Files........................................ 10.1.3 Properties of Files.......................... 10.1.3.1 File Name.......................... 10.1.3.2 File Position...................... 10.1.3.3 Formatted and Unformatted Files •••••••••••••••••••.•••••••••• 10.1.3.4 Sequential and Direct Access Files ............................. . 10.1.4 Internal Files ••••••••••••••••••••••••••••••• 10.1.4.1 Special Properties of Internal File s ............................. . 10.1.5 Units •••••••••••••••••••••••••••••••••••••••• 10.2 General Discussion of the Input Output System •••••••• 10.2.1 Pre-Connected Files •••••••••••••••.•••••••••• 10.2.2 Examples of Common Input Output Opera- tions ....................................... . 10.2.3 10.2.4 Less Common File Operations •••••••.•••••••••• Limitations of FORTRAN Input Output System •••••••••••••••••••••••••••••••••••••••••• o 73 73 73 74 74 74 75 75 75 76 76 76 77 78 78 79 80 10.2.4.1 10.3 Direct Files must be on Blocked Dev ices •••••••••••••••••••••••••••• 10.2.4.2 No Character Compression in Direct Files •••••••••••••••••••••••••••••• 10.2.4.3 BACKSPACE Only Applies to Files on Blocked Devices •••••••••.•••••••••• 10.2.4.4 Length Limitations on Formatted Records ••••••••.••••••••••••••••••• 10.2.4.5 BACKSPACE may not be used on Unformatted Sequential Files ••••••• 10.2.4.6 Side Effects of Functions Used in Input Output Statements •.•.•••••••• Elements of Input and Output Statements •••.•••••••••• 10.3.1 The Unit Specifier 'u' ••••••••••••••••••••••• 10.3.2 The Format Specifier 'f' ••••••••••••••••••••• 10.3.3 The Record Number 'rn' •••••••••.••••••••••••• 10.3.4 The End of File Exit Specifier •..•..•.•..••.• 65 65 66 67 68 68 69 69 69 69 70 71 - iii - 80 80 81 81 81 81 81 81 82 83 83 10.3.5 The Error Exit Specifier ••••••••••••••••••••• The Input Output Status specifier ·ios· •••••• 10.3.7 The Input-Output List 'iolist' ••••••••••••••• 10.3.7.1 Input and Output Objects •••• ~ •••••• 10.3.7.2 Implied DO Lists ••••••••••••••••••• The Specific Input and Output Statements ••••••••••••• 10.4.1 OPEN Statement ••••••••••••••••••••••••••••••• 10.4.2 CLOSE Statement •••••••••••••••••••••••••••••• 10.4.3 READ, WRITE and PRINT Statements ••••••••••••• 10.4.4 File Positioning Statements •••••••••••••••••• 10.4.4.1 BACKSPACE Statement - Backspace a File............................... 10.4.4.2 ENDFILE Statement - Write an Endfile Record........................ 10.4.4.3 REWIND Statement - Rewind a 10.3~6 10.4 10.4.5 10.5 File............................... INQUIRE Statement - Obtain File Properties ........................................ . List Directed Input and Output ••••••••••••••••••••••• 10.5.1 List Directed READ ••••••••••••••••••••••••••• 10.5.1.1 List Directed Value Separators............................... 10.5.1.2 List Directed Input Values......... 10.5.2 List Directed WRITE and PRINT................ Chapter 11 - Pormat Specifications •••••••••••••••••••••••••• 11.1 FORMAT Specifications and the FORMAT Statement •.••••• 11.2 Interaction Between Format Specifications and I/O Lis t ..•....•....•.•••.•..••........•.....•..•..•....• 11.3 Edit Descriptors ••••••••••••••••••••••••••••••••••••• 11.3.1 Repeatable Edit Descriptors •••••••••••••••••• 11.3.1.1 Numeric Editing •••••••••••••••••••• 11.3.1.2 I - Integer Editing •••••••••••••••• 11.3.1.3 F - Real Editing ••••••••••••••••••• 11.3.1.4 E and D - Real Editing ••••••••••••• 11.3.1.5 G - Real Editing ••••••••••••••••••• 11.3.1.6 Formatting Extreme Values •••••••••• 11.3.1.7 L - Logical Editing •••••••••••••••• 11.3.1.8 A - Character Editing •••••••••••••• 11.3.2 Non Repeatable Edit Descriptors •••••••••••••• 11.3.2.1 'xxx' - Apostrophe Editing ••••••••• 11.3.2.2 H - Hollerith Editing •••••••••••••• 11.3.2.3 X and T - Positional Editing ••••.•• 11.3.2.4 Slash Editing - End of Transfer on Record ••••••••..••••••••••••••••••• 11.3.2.5 Backs1ash or Dollar Editing Inhibit End of Record •••••••••••••• 11.3.2.6 Colon Editing - Conditional Termination ••••••••••••••••••••••••••••• 11.3.2.7 P - Scale Factor Editing ••••••••••• 11.3.2.8 BN and BZ - Blank Interpretat ion •.•...••••.••.•••••..•••.•..•.• - iv - 83 83 84 84 85 85 85 87 88 89 90 90 90 91 95 95 95 95 97 99 99 101 103 103 103 104 104 105 105 106 107 107 107 107 108 108 109 109 110 110 III S, SS and SP - Sign Control Editing. . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . III Chapter 12 - Program and Subprogram Structure ••••••••••••••• 12.1 Main Program ••••••••••••••••••••••••••••••••••••••••• 12.2 Access To Command Line Arguments .••••••••••••••••••••• 12.3 Formal Arguments and Actual Arguments •••••••••••••••• 12.3.1 Argument Association ••••••••••••••••••••••••• 12.4 Subroutines •••••••••••••••••••••••••••••••••••••••••• 12.4.1 SUBROUTINE Statement ••••••••••••••••••••••••• 12.4.2 CALL Statement ••••••••••••••••••••••••••••••• 12.5 Functions ........................................... . 12.5.1 External Functions ••••••••••••••••••••••••••• 12.5.2 Intrinsic Functions •••••••••••••••••••••••••• 12.5.3 Statement Functions •••••••••••••••••••••••••• 12.6 ENTRY Statement •••••••••••••••••••••••••••••••••••••• 12.6.1 Restrictions on the ENTRY Statement •••••••••• 12.7 RETURN Statement ••••••••••••••••••••••••••••••••••••• Definition Status •••••••••••••••••••••••••••••••••••• 12.8 12.9 BLOCK DATA Subprogram •••••••••••••••••••••••••••••••• 12.10 The FORTRAN Intrinsic Functions •••••••••••••••••••••• 113 113 114 115 115 117 117 118 119 120 121 121 122 123 124 125 125 126 Chapter 13 - FORTRAN Compile Time Options ••••••••••••••••••• 13.1 $INCLUDE - Include Source File ••••••••••••••••••••••• 13.2 $XREF - Generate Cross Reference ••••••••••••••••••••• 13.3 $SEGMENT - Designate Segment Name •••••••••••••••••••• 13.4 $COL72 - Restrict Source Lines to 72 Columns ••••••••• 13.5 FORTRAN-66 Compatibility Options ••••••••••••••••••••• 13.5.1 $F66oo - Implement FORTRAN-66 DO Loops ••••••• 13.5.2 $CHAREQU - Character and Numeric Data Equivalence ••••.•••••••••.••••••••••••••••••• 13.5.3 $INT2 - Make Integers l6-Bits •••••••••••••••• 129 129 129 129 130 130 130 Appendix A - Messages from the FORTRAN System ••••••••••••••• A.1 Compile-Time Error Messages •••••••••••••••••••••••••••• A.2 Run-Time Error Messages •••••••••••••••••••••••••••••••• 133 133 139 Appendix B - Intrinsic Functions •••••••••••••••••••••••••••• B.1 Notes on the Intrinsic Functions ••••••••••••••••••••••• B.2 Restrictions on Ranges of Arguments.................... B.3 Non Standard Intrinsic Functions and Subroutines ••••••• B.3.1 POKE - Store Into Arbitrary Memory Location. • • • • • • • • • • • • • • • • • • • • • • • • • • • •• • • • •• • • • • • • • • • B.3.2 IPEEK - Read From Arbitrary Memory Loca- 143 146 147 148 11.3.2.9 130 130 148 VERS - Print Date and Version ••••••••••••••••••• RAN - Random Number Generator ••••••••••••••••••• IARGC - Number of Arguments ••••••••••••••••••••• GETARG - Access an Argument ••••••••••••••••••••• 148 148 149 149 149 Appendix C - Data Representations ••••••••••••••••••••••••••• C.l Storage Allocation ••••••••••••••••••••••••••••••••••••• C.2 Data Representations .••••.••••.•••.••.••••••••••••.•••• 151 151 152 tion ........................................... . B.3.3 8.3.4 B.3.5 8.3.6 - v - C.2.l C.2.2 C.2.3 C.2.4 Representation of Integers •••••••••••••••••••••• Representation of REAL and DOUBLE PRECISION. • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • . • • • • • • • • • Representation of Extreme Numbers •••••.••••••••• Hexadecimal Representation of Selected 153 153 154 Numbers. • • • • • • • • • • . • • • • . • • • • . • • • • • • • • • . • • • • • • • • • 155 C.2.5 Deviations from the Proposed IEEE Standard...... C.2.6 Arithmetic Operations on Extreme Values ••••••••• C.2.7 Representation of Logicals •••••••••••••••••••••• C.2.8 Storage of Arrays ••••••••••••••••••••••••••••••• Argument Passing Mechanism •••••••••••••••••••. ~ •••••••• Function Results •••••••••••••••••••••••••••••.••••••••• Register Conventions ••••••••••••••••••••••••••••••••••• 155 155 159 159 159 160 160 Appendix D - ASCII Character Set Table •••••••••••••••••••••• 161 Appendix E - Operating the SVS FORTRAN Syste•••••••••••••••• E.l System Components •••••••••••••••••••••••••••••••••••••• E.l.l Compiler Front End •••••••••••••••••••••••••••••• E.l.2 Code Generator •••••••••••••••••••••••••••••••••• E.l.3 Linker •••••••••••••••••••••••••••••••••••••••••• E.l.4 Libraries ••••••••••••••••••••••••••••••••••••••• E.l.5 Error Messages •••••••••••••••••••••••••••••••••• E.2 Command Line Directives and Compiler Options •.••••••••• E.3 Linking Programs which Utilize Pascal and C •••••••••••• E.3.l What Language must Supply the Main Program •••••• E.3.2 Referring to the Command Line Arguments ••••••••• E.3.3 Dynamic Memory Allocation and Deallocation •.•••• E.3.4 Parameter Conventions ••••••••••••••••••••••••••• E.3.4.l· Calling FORTRAN from Pascal •••••••••••• E.3.4.2 Calling Pascal from FORTRAN •••••••••••• E.3.4.3 Calling C from PORTRAN •••••••••.••••••• E.3.4.4 Calling FORTRAN from C .••.•••••.••••••• E.3.S Run Time Libraries •••••.•••••••••••••••••••••••• E.3.6 Upper and Lower Case External Naming Convent ions ••••••••••••••••••••.••••••••••••••••.••••• 163 163 163 164 164 164 165 165 166 167 167 167 167 168 168 168 169 170 Appendix F - CPM Operating Syste. Specific Infor.ation •••••• F.l Compiling a Simple Program ••••••••••••••••••••••••••••• F.2 Error Message Files •••••••••••••••••••••••••••••••••••• F.3 Ulinker •••••••••••••••••••••••••••••••••••••••••••••••• P.3.l Ulinker Inputs •••••••••••••••••••••••••••••••••• F.3.2 Ulinker Outputs ••••••••••••••••••••••••••••••••• F.3.3 Running Ulinker from the Command Line ••••••••••• F.3.4 Running Ulinker Interactively ••••••••••••••••••• F.3.5 Running Ulinker with Standard Input Redirected...................................... F.3.5.l Symbol Table Information Placed in Output File............................ F.3.6 Treatment of Unresolved External References........................................... F.3.1 Segments........................................ F.3.8 Errors Detected by Ulinker....................... F.4 Linking to CPM Assembly Code........................... P.5 Access to Command Line Arguments....................... 113 173 114 174 114 174 177 177 C.3 C.4 C.5 - vi - 171 178 178 178 118 178 179 180 Chapter 1 Introduction Cbapter 1 - Introduction FORTRAN is a.computer programming language oriented towards numerical co.putations. PORTRAN-77 is the latest Cat the time of this writing) offering of the ANSI standardization committee. This FORTRAN reference manual describes the language called FORTRAN-77, as iaplemented by Silicon Valley Software, Inc. (SVS). Pro. now on, the word FORTRAN is used to mean this implementation of PORTIAN-77. 1.1 Overview of the FORTRAN Language A FORTRAN program is (ultimately) composed of characters. Characters are grouped into lines. Lines are grouped into program units. Program units are grouped into programs. A line is either a comment line, an initial line of a statement or a-continuation line of a statement. Lines appear in columns 1 thru 120. For compatibility with older FORTRAN implementations, the SVS FORTRAN-77 compiler will ignore lines past column 72 if the user selects the $COL72 compiler option (see Chapter 13 "FORTRAN Compile Time Options" for a description of the compiler options.) Comment lines are blank lines, as are lines with the letter C (upper-case or lower-case) or the asterisk character "*" in column one. Comment lines can appear anywhere in a FORTRAN program, including between initial lines and continuation lines of a statement. The initial line of a statement has a zero or a space character in column 6. A continuation line of a statement has any other character in column 6. A continuation line is also signaled by. an ampersand character C&) appearing in column one of a source line. Statements may have up to 19 continuation lines. The initial line of a statement may have a statement label in columns 1 thru 5. A statement label is one to five digits-rn-length. At least one of the digits must be non-zero. A statement label serves to "tag" a statement so that it can be referenced by other statements. Fortran R~ference Manual Page 1 Introduction Chapter 1 Statements are broadly divided into the two groups of executable and non-executable. Executable statements perform program actions that assign values to variables, evaluate expressions, affect flow of execution and perform data transmission. Nonexecutable statements generally are those that specify the forms and attributes of program objects. Statements are discussed in more detail a few paragraphs further on. Program objects include constants and variables. A constant is a string of digits or other characters defIning a value that does not change. Variables occupy storage and have values that can be changed during program execution. Variables and constants can have both a name and a data~. The name serves to identify that object--rn a program. The type of a data object defines, among other things, the amount of storage it occupies, its range and precision, and in some cases, the operations that can be performed on it. FORTRAN names can have default data types derived from a naming convention or the default rules can be overridden by explicit specifications. A variable can be a single object or it can be an aggregate. There are two forms of aggregate data objects, namely arriY variables and character variables. An array variable is a co lection of data occupying consecutive storage units. Arrays can have up to seven dimensions. A character variable represents string data and is a sequence of characters, which can be accessed individually, or collectively, in the form of a substring. A complete FORTRAN program is composed of a main program and any number of subprograms. Subprograms fall into the categories of SUBROUTINE subprograms which can be activated via the CALL statement to perform out-of-line groups of statements, FUNCTION subprograms which compute and return a value in the context of an expression, and BLOCK DATA subprograms which serve to initialize data declared in COMMON blocks. The main program and subprograms form what are called program units. In general, the terms "subprogram" and ·program unit" can be used interchangeably. Userdefined subroutines ~nd functions are also called "procedures". A variable may be given more than one name by a process of association. There are several ways to associate data. The COMMON statement provides a way to share data between separate program units. The EQUIVALENCE statement associates variables in the same program unit. Variables may also be associated through the argument passing mechanism when subroutines or functions are referenced. Names of variables have a scope which is dependent on the way that they are defined. In general, most names (except names of program units, common areas and certain other names) have a scope that is local to the program unit in which they are defined. A name defined by being called as an external function has a global scope by default. Names defined in a common area are local Page 2 Fortran Reference Manual Chapter 1 Introduction to the program unit in which they are declared. The name of the common area itself is global. Formal parameters to statementfunctions have a scope which is local to the statement-function statement itself. Specification statements are one of the two major groupings of 'statements. Specification statements serve to declare variables and symbolic constants. Specification statements include the ~ statement for defining the data type of a variable, the DIMENSION statement to define the size of array variables, the COMMON and EQUIVALENCE statements to provide association of variables, the PARAMETER statement to give a symbolic name to a constant and the EXTERNAL and INTRINSIC statements to define attributes of other program units. The DATA statement provides a mechanism for static initialization of data. The DATA statement includes an implied DO 190P construct to facilitate initializing array variables in a conC1se manner. Expression~ combine data objects and operators to create new values. FORTRAN supports arithmetic, character, logical and relational expressions. Mixed-mode expressions are permitted, with well defined rules for conversions between the operands and generation of the result. The assignment statement assigns the value of an expression to a variable. There are three variations of assignment, namely arithmetic, character and logical. The ASSIGN statement serves to assign the value of a statement label to an integer variable. Control statements are those that control the flow of execution in a program. Various kinds of IF statements select other statements for execution, depending on the result of evaluating a logical or arithmetic expression. The DO statement provides for repetition of a block of statements while a control variable is assigned a sequence of values. The CALL and RETURN statements provide for subroutine and function execution. Variations of the GO TO statement provide for transfer of control within a program unit. Statement-function statements are characterized by a singlestatement "template" defined in a program unit, with operations on dummy arguments. The statement function is referenced in a program unit just like a function, with actual arguments supplied. The arguments are combined according to the statementfunction definition to yield a result that can be used in an expression. FORTRAN provides a powerful iaPut and output capability. A file can be external (connecte to an external device) or internal (refers to a character variable). Files can be formatted or unIormatted. Files can be accessed sequentially or randomly. Fortran Reference Manual Page 3 Introduction Chapter 1 files can be the subject of data conversion operations from internal storage representations to external character string representations and vice-versa. Formatt~d Format conversion is performed via READ, WRITE or PRINT statements. There is a rich set of format specifications to control the form and layout of converted data. There is a list-directed input-output capability, where default formatting--tules are applied to the conversion process. SUBROUTINE and FUNCTION program units may have arguments which a calling routine passes to them for processing. At the time a subroutine or function is declared, its formal arguments are declared. At the time the subroutine or funct10n is referenced, actual arguments are substituted. for the formal arguments. A subroutine or function may have multiple ENTRY points. An ENTRY statement can cause execution of a subroutine or function to begin at a statement other than the first executable statement. Control is returned from a subroutine or function program unit either by encountering the END statement, or by executing a RETURN statement. FORTRAN provides for an alternate return specification for ~ubroutines, such that a subroutine can return to a different place in the caller than the statement following the CALL statement. FORTRAN supplies a comprehensive set of intrinsic functions which perform data type conversion and provide an extensive collection of arithmetic and transcendental functions. 1.2 Notation and Terminology Used in this Manual This section defines the notation that is used in to define FORTRAN language constructs. this manual Upper-case letters and special characters are written as shown in programs. Lower-case letters and words indicate objects for which there is a substitution in actual statements described in the text. Once a lower-case object is define~, it can be assumed to retain that meaning for the remainder of the construct being defined. Example of ~-case and. lower-~ usage The format specification which describes integer editing is denoted Iv, where v is a non-zero, unsigned integer constant. In an actual. FORMAT statement, the editing specification might be written as IS or 121. The editing specification for real numbers is Fw.d, where d is an unsigned integer constant. An actual FORMAT statement might contain an edit specification like PS.4 or P14.0. Note that the period character is a special character as defined above, and is taken literally. Page 4 Fortran Reference Manual Introduction ."pter 1 Brackets "[" and ")" enclose optional items. For example, A[w) indicates that either of the forms A or Al2 are valid (as a means of specifying a character format). The ellipsis notation " ••• " indicates that the optional item preceding the ellipsis may appear one or more times. For example, the computed GOTO statement is described by the form: GOTO ( s [, s ] ••• ) [, ] i which indicates that the syntactic item ',Sf may be repeated number of times. any Spaces (blanks) normally have no significance in describing FORTRAN statements. The general rules for spaces, supplied later in this chapter, provide the interpretation of spaces in all contexts. Throughout this manual, "space" and "blank" are considered synonymous. In general, the word "space" is used. 1.3 Basic Elements of FORTRAN This section covers the basic lexical and syntactic that go towards constructing a FORTRAN program. 1.3.1 elements FORTRAN Character Set The FORTRAN character set consists of letters, digits, and special characters. upper and lower case A letter is one of the S2 characters: ABC D E F G H I J K L M N 0 P 0 R STU V W X y Z abc d e f 9 h i j kIm n 0 p q r s t u v w x y z A digit is one of the ten characters: o 1 234 S 6 789 An alphanumeric character is a letter or a digit. The special characters consist of the following characters: Fortran Reference Manual Page S Chapter 1 Introduction +-----------+-------------------+ I Character I Name of Character I +-----------+-------------------+ Blank or Space + * / \ ( ) . $ • , Equals sign Plus sign Minus sign Asterisk Slash Reverse Slash Left Parenthesis Right Parenthesis Comma Decimal Point Currency Symbol Apostrophe Colon Ampersand +-----------+-------------------+ 1.3.2 Collating Sequence and Graphics SVS FORTRAN uses the sequence in ASCII is: ASCII character set. The collating • Space (blank) collates lowest, followed by: • Digits "0" thru "9", followed by: • Upper case letters "A" thru "Z", followed by: • Lower case letters "a" thru "z". The special characters appear in between digits and upper-case letters and before and after lower-case letters. There is an ASCII character set chart in the appendices. Within each of the ordered sets, digits, upper-case letters, and lower-case letters, the characters in those sequences are contiguous - there are no "holes" in those sequences. 1.3.3 Use of Spaces or Blanks or Tabs· The tab character is interpreted in all cases by SVS FORTRAN as a series of one or more blanks, sufficient to fill columns up to and including the next column position evenly divisible by eight. All references to blanks in this manual may refer to actual blanks or blanks resulting from the interpretation of tab characters. All references to columns in this manual refer to the columning after the interpretation of tabs. Limitations on the Page 6 Fortran Reference Manual Chapter 1 Introduction total number of characters per line and per statement are after the interpretation of tabs. The space (also called blank) character has no meaning in a program unit, with the exceptions listed below. Otherwise, spaces can be used freely to improve the layout and readability of a program. Spaces are significant in the following cases: Within string constants, and within Hollerith fields. On compiler directive lines, "Using the FORTRAN Compiler". discussed in the chapter In column 6, where a space distinguishes an initial line a continuation line. Counting in the total number of characters per statement. Fortran Reference Manual line on from and per Page 7 Introduction Page 8 Chapter 1 FORTRAN Reference Mar Lines, Statements, and Control Flow Chapter 2 Chapter 2 - Lines, Statements, and Control Flow This chapter consists of three sections. The first section describes the notions of lines in a FORTRAN program. The second section covers the rules for FORTRAN statements. The final section in this chapter covers the concept of execution sequence or control flow - the order in which FORTRAN statements are executed. 2.1 Lines A line in a program unit is a sequence of characters in columns thru 120 (1 thru 72 if the $COL72 compiler option is selected, as described in Chapter 13). All characters in a line must be selected from the character set described in Chapter 1. Comment lines (described below), character constants and Hollerith fields can contain any printable ASCII character. 1 The character positions on a line are called columns and are numbered consecutively from 1 thru 120 (1 through 72), left to right on a line. The FORTRAN compiler ignores characters which appear to the right of column 120 (column 72 if the $COL72 compiler option is selected) on a line, thus the user may use these columns for any purpose (such as sequence information). 2.1.1 Comment Lines Comment lines can appear anywhere in a program unit, including before the first statement or after the last statement of a program unit. Comment lines may appear between an initial line and its first continuation line, or between two continuation lines. FORTRAN .Reference Manual Page 9 Chapter 2 Lines, Statements, and Control Flow Examples of Comment Lines C * C This is a comment line. This is also a comment line. The line following this one is all blank ••••• c ..... and is therefore considered to be a comment. ** * Comment lines are for documentary purposes and have no effect on compilation or execution. 2.1.2 Initial Lines An initial line generally indicates the start of a statement line. An initIal line is any non-comment line containing the space character or the digit 0 in column 6. Columns I thru 5 of the initial line of a statement may contain a statement label. Since a line which begins with a tab character is processed as if it had 8 initial blanks, such lines are interpreted as initial lines. If a tab character follows a statement label which occupies some or all of the first 5 columns, the line will also be processed as if it had a blank in column 6. Examples of Initial Lines Here are initial lines without statement labels. C C GO TO 999 OGO TO 999 C C Here are initial lines with statement labels. C 379 GO TO 999 4850GO TO 999 2.1.3 Continuation Lines A continuation character from character or the character , in statement label. statement. Page 10 line is any non-comment line containing any the FORTRAN character set (other than a space digit 0) in column 6, or having the ampersand column one. A continuation line must not have a There may be up to 19 continuation lines in a FORTRAN Reference Manual Lines, Statements, and Control Flow Chapter 2 Examples of Continuation Lines C C C * * , 2.1.4 These contrived statements each span two lines. GO TO $ 999 843 GO TO + 999 GO TO 999 Compiler Directive Lines Compiler Directives are an SVS extension to FORTRAN-77. Compiler directives provide additional controls over the compiler's actions. A compiler directive line is a line with a dollar sign "$" in column 1. A compiler directive line can appear anywhere that a comment line can appear, although certain directives must appear in certain restricted places in the program. Spaces are signi~icant in compiler directive lines and serve to delimit keywords and filenames. The compiler directives are listed in the chapter on "Running the FORTRAN Compiler". Examples of Compiler Directives * The following directive * include the body of the * program source code. * * $INCLUDE rasp. text 2.2 instructs the compiler to file 'rasp.text' into the Statements FORTRAN language statements are described in 12. Statements are used to form program units. Chapters 6 thru Statements are written in columns 7 thru 72 of an initial line, and as many as 19 continuation lines. An END statement is the exception to the above rules. An END statement must appear on an initial line on its own. No other statement in a program unit may have an initial line that looks like an END statement. FORTRAN Reference Manual Page 11 Lines, Statements, and Control Flow Chapter 2 In general, statements must begin on new lines, that is, a statement may not begin on the same line as another statement. The exception to this rule is the logical IF statement. Spaces before, within, and after statements have no effect, except within character constants and Hollerith constants, where they indicate blank characters. Examples of Statements C An assignment statement C A = 5.0 C C A subroutine call statement C CALL COLECT(PAY, PHONE) C C A logical IF statement C IF (DAY .EO. 'FRIDAY') 2.2.1 RETURN Statement Labels Statement labels provide the means to "tag" that other statemen~s may refer to it. a statement such Any statement may be labeled, but only labels associated with executable statements and FORMAT statements can be referenced by other s~atements. A statement label is one to five digits appearing anywhere in columns 1 thru 5 of the initial lfne of a statement. At least one of the digits in a statement label must be non-zero. In any given program unit, statement labels must duplication of statement labels is an error. be unique Examples of Statement Labels 123 C C C FORMAT('The result is', IS) An example of a DO block. DO 110 ICON 1, 100 DESK (ICON) = 0.0 110 CONTINUE Page 12 FORTRAN Reference Manual Chapter 2 2.2.2 Lines, Statements, and Control Flow Order of Statements and Lines In any given program unit, the order in which statements appear must obey certain rules. These rules are detailed below. A PROGRAM statement may appear only as the first statement of a main program. The first statement of a subprogram must be either a FUNCTION, SUBROUTINE, or a BLOCK DATA statement. In a program unit, statements order. must appear in the following 1. FORMAT statements can appear anywhere. 2. All specification statements must precede all DATA statements, statement-function statements, and executable statements. 3. All statement-function statements must precede able statements. 4. DATA statements may appear anywhere after the statements. 5. ENTRY statements may appear anywhere except between a block IF statement and its corresponding END IF statement or between a DO statement and the terminal statement of its DO-loop. In other words, a subprogram must not be entered (via an ENTRY statement), in the middle of a block IF or DO block. all execut- specification within a program unit's specification statements, IMPLICIT statements must precede all specification statements other than PARAMETER statements. Any specification statement that defines the type of a symbolic name must precede a PARAMETER statement that defines the symbolic name of a constant. PARAMETER statements that define symbolic constant precede all uses of such names. names The last (non-comment) line of a program unit must statement. be The diagram below pictorially describes the manner statements and comment lines may be interspersed. FORTRAN Reference Manual an in must END which Page 13 Chapter 2 Lines, Statements, and Control Flow I+--------------+--------------+-----------------+I I+-----------------+I ~----------+-----------------------------------------------+ PROGRAM, FUNCTION, SUBROUTINE, or BLOCK DATA statement. IMPLICIT Statements comment Lines FORMAT and ENTRY Statements PARAMETER Statements Other Specification Statements +--------------+-----------------+ Statement DATA Statements Function statements +-----------------+ Executable I I Statements ~----------+--------------+--------------+-----------------+ I I END Statement ~----------------------------------------------------------+ Figure 2-1 Ordering of Lines and Statements in a FORTRAN Program In the diagram, vertical lines separate statement groups that may be mixed. For example, FORMAT statements can be mixed with statement-function statements and executable statements. Horizontal lines separate statement groups that must not be mixed. For example, statement-function statements cannot be mixed with executable statements. Note that an END statement, in addition to being executable, must be the last statement in a program unit. 2.3 Execution Sequence and Control Transfer Normal execution sequence means that executable statements are executed in the order in which they appear in the program unit. Program execution starts with the first executable statement in the main program. When an external procedure is referenced, execution proceeds with the first executable statement that follows the FUNCTION, SUBROUTINE or ENTRY statement in the subprogram. A control transfer means that the normal execution sequence altered. Statements that cause control transfer are: 1. unconditional GO TO statement, computed GO TO assigned GO TO statement, Page 14 statement is or FORTRAN Reference Manual Chapter 2 Lines, Statements, and Control Flow 2. Arithmetic IF statement, 3. RETURN statement, 4. STOP statement, 5. input-output statement containing an error specifier end-of-file specifier, 6. CALL with an alternate return specifier, 7. logical IF statement containing any of the its subordinate statement, 8. Block IF and ELSE IF statements, 9. the last statement (if any) of an IF-block or ELSE IF-block, 10. DO statement, 11. the terminal statement of a DO-loop, 12. END statement. above or an forms as Normal execution sequence is not affected by non-executable statements, comment lines or compiler directives appearing between executable statements in the source code. Executing a function reference or a CALL statement is not considered a control transfer in the program that makes the reference, except when control is returned to a statement identified by an alternate return specifier in a CALL statement. Executing a RETURN or an END statement in a referenced procedure, or a control transfer in a referenced procedure, is not considered a control transfer in the program unit that makes the reference. Function and subroutine subprograms cannot be invoked recursively in SVS FORTRAN. Note, however, that FORTRAN subprograms can reference subprograms written in other languages (such as Pascal) that themselves can be recursive. FORTRAN Reference Manual Page 15 Lines, Statements, and Control Flow Page 16 Chapter 2 FORTRAN Reference Manual Data Types. and Constants Chapter 3 Chapter 3 - Data Types and Constants There are six data ~ in FORTRAN, namely: INTEGER, REAL (floating point), DOUBLE PRECISION (extended precision REAL), COMPLEX (elements of the complex number domain), CHARACTER (character string data) and LOGICAL (able to assume the values .TRUE. or .FALSE.). The various data types are discussed in the sections to follow. SVS FORTRAN extends ANSI FORTRAN in such a way that the user can specify the amount of computer storage which a particular data type consumes. This extension is covered in the appropriate sections below. 3.1 Data Type Rules A symbolic name -(associated with a constant, variable, array, external function or statement-function) can have its type specified in a type statement. The possible types are those listed in the paragraph above. If no explicit type statement is supplied for a program element, the type is implied by the first letter of the name. A first letter of I, J, X, L, M or N implies type integer. Any other first letter implies type real. These default type rules can be overridden either by explicit type statements or by the IMPLICIT statement, which changes the default type-rules. The data type of an array element is the same as that of the array. The data type of a function name specifies the type of the value which that function returns. Intrinsic functions have a type that is specified in the chart in the chapter on "Program Structure". Generic intrinsic functions do not have a default type. The type of a generic intrinsic function depends on the type of its argument(s). An external function reference is given a default type, based upon the first letter of its name, in the same way as variables and arrays. 3.2 Constants A constant is a value that defines itself and does not change. A constant can be an arithmetic value, a logical value, or a character string value. The representation of a constant FORTRAN Reference Manual Page 17 Chapter 3 Data Types and Constants specifies both its value and its data type. A PARAMETER statement associates a symbolic name with a constant. Arithmetic constants are INTEGER, REAL, DOUBLE COMPLEX values. PRECISION, and For the purposes of definition in this manual, an unsigned constant is a constant without any leading sign. A signed constant is a constant with a leading plus or minus sign. An optionallysigned constant is a constant that can be either signed or unsIgned. Integer, real, and double precision constants may be optionally-signed except where otherwise noted. 3.3 Integer Data Type Integers, as represented in the finite word size of a computer, are only a subset of the infinite set of integers. An integer value as represented in FORTRAN is an exact representation of the corresponding integer. An integer data value occupies two words (four bytes or 32 bits) of storage and can represent values in the range -2,147,483,648 thru +2,147,483,647. Integers can be designated as fitting in 16 bits if the $INT2 compiler option is selected. Integer numbers are internally stored in two's complement representation. As a consequence, there is one more negative integer value than there are positive integer values. SVS FORTRAN also provides a means to specify the amount of storage which integers occupy_ This is an extension to ANSI FORTRAN. The extended forms of integer are: INTEGER*l occupies one byte (8 bits) and can assume in the range -128 thru +127. values INTEGER*2 occupies one word (16 bits) and assumes values in the range -32768 thru +32767. INTEGER*4 9ccupies two words (32 bits) and is the same the standard integer type discussed above. as An integer constant consists of a sequence of decimal digits, preceded by an optional sign. Alternatively, an integer constant can be expressed in the hexadecimal radix by a dollar sign ($) followed by a sequence of digits or letters in the range 'A' through 'F' or 'a' through If'. Note that hexadecimal numbers are considered unsigned. To obtain a signed hexadecimal constant, the user must explicitly code a 1 in the sign bit position. Page 18 FORTRAN Reference Manual Data Types and Constants Chapter 3 Examples of INTEGER Constants 3.4 72 -32768 32767 o $123 $ffffffff $Oa $3e8 +56 Real Data Type Real Data Types are intended to represent the set of real values which comprise the continuum. Because of a finite representation imposed by a finite word size in the computer, the real data type in FORTRAN can only represent a finite subset of the entire set of reals. A basic real constant has an optional sign, an integer part, a decimar--point, and a fractional part. Both the integer and the real part are sequences of digits. Either part can be omitted, but not both. Real constants are assumed to be decimal numbers. Examples of Basic Real Constants 3.14159 .7071 5. 0.0 +2.236 +.5 +8. -1.4142 -.618034 -6. O. .0 A real exponent consists of the letter E followed by an optionally--signed integer constant. A real exponent indicates a power of ten. Examples of Real Exponents E14 E+12 E-10 EO A real constant is anyone of: a basic real constant, a basic real constant followed by an exponent part, or an integer constant followed by an exponent part. SVS FORTRAN provides a means to specify the amount of data storage which a real data type is to occupy. The forms are: REAL*4 occupies two words (32 bits) and is the same as a basic real datum as described above. FORTRAN Reference Manual Page 19 Data Types and Constants REAL*8 Chapter 3 occupies four words (64 bits) and is the same as the DOUBLE PRECISION data type discussed below. Examples of Real Constants +1.52E-l 299193.5E3 20E-3 A real constant containing an exponent part is the product of the constant preceding the E and the power of ten indicated by the integer following the E. A real value occupies four bytes of storage. The range of real values is approximately -3.4E38 thru +3.4E38. The precision is about seven decimal places. 3.4.1 Infinite and Indeterminate Real Values The representation of real values in FORTRAN allows for positive and negative "infinity", and for indeterminate values. This is primarily of interest when formatting such values for output. When output by a FORTRAN program, these values appear as strings of either plus signs '++++.+++' or minus signs ,----.---' for positive and negative infinity, and as question marks '7771.111' for indeterminate values. There is more on this subject in the chapter on input and output. 3.5 Double Precision Data Type The Double-Precision data ~ is intended for applications where the range and precision of Single-Precision data is inadequate. Double-Precision extends the range to approximately -10E308 thru +10E308 and the precision to about 16 decimal digits. A double precision exponent is the letter D followed by an optionally-signed integer constant. The forms of a double precision constant are either: a basic real constant followed by a double precision exponent, or an integer constant followed by a double precision exponent. 3.6 Complex Data Type The Complex data domain. ~ represents values from the complex number A complex number consists of an ordered pair of numbers, each of which is either an integer or a single-precision real number the first representing the "real" part of the number, and the Page 20 FORTRAN Reference Manual Data Types and Constants Chapter 3 second representing the -imaginary- part. A complex constant is written as two integers or single-precision real numbers enclosed in parentheses and separated by a comma. Examples of Complex Constants (1, 1) 3.7 (0.707, -0.707) (-1.5ElO, 2.6E-5) Character Data Type A character data element is a string of characters. The string can contain any of the printable ASCII characters. Spaces are significant in character strings. The length of a character string is the number of characters in the str1ng. The form of a character constant is a non-empty string of characters enclosed in apostrophe "I" signs. The apostrophes serve to delimit the string constant, but are not part of it. An apostrophe in the string is represented by two juxtaposed apostrophes. The length of a character constant is the number of characters in the string, except that each pair of juxtaposed apostrophes in the string is counted as one character. The delimiting apostrophes are not part of the string and are not counted in the string length. The maximum length of a character constant is 255 characters. There is no provision for strings. expressing empty (null) character Examples of Character String Constants 'x' I , 'The time is One O"Clock' 'The hunting of the Snark' " .. The last two examples illustrate the representation apostrophes. of embedded FORTRAN source lines may extend up to column 120 (or 72 if $COL 72 set) on a line. Shorter lines are not space-filled to 72 columns but are left as typed. When a character constant extends across a line boundary, its value is as if the portion of the continuation line starting in column 7 abuts the last character on the preceding line. Thus the FORTRAN source statement: FORTRAN Reference Manual Page 21 Chapter 3 Data Types and Constants 200 example. 'First string ~art$ Second string part' (where is carriage-return) is equivalent to the statement: 200 example = 'First string part Second string part' where the single space between the "t" at the end of the first line and the "S~ at the start of the secdnd line is the space in column 7 of the continuation line. Long character constants can be represented in this way. 3.8 Logical Data Type A logical data element represents a Boolean quantity. only take on the values true or false. It can The form of a logical constant is either: ".TRUE." (representing the truth value) or ".FALSE." (representing the false value). SVS FORTRAN provides a means to specify logical data items which occupy less data storage than the standard logical type. These forms are: LOGICAL*l occupies one byte (8 bits). LOGICAL*2 occupies one word (16 bits). LOGICAL*4 occupies two words (32 bits) and is the the standard LOGICAL data type. Page 22 same as FORTRAN Reference Manual FORTRAN Names, Arrays, and Substrings Chapter 4 Chapter 4 - FORTRAN Names, Arrays, and Substrings This chapter introduces the rules for FORTRAN ~ - symbolic names which may be used to identify program objects. The second section describes the way that arrays are defined and referenced. The third section discusses the ideas of character variables and substrings of character variables. 4.1 FORTRAN Names A FORTRAN name or identifier consists of one through six alphanumeric characters, and must start with a letter. A FORTRAN name 'can have embedded spaces in it - the spaces have no significance and are ignored. The FORTRAN compiler makes no distinction between upper-case letters and lower-case letters the names PASCAL, PaSeAl, pAsCaL and pascal are all equivalent as far as FORTRAN is concerned. A name is used to denote a user-defined variable, a systemdefined variable, array variable, subroutine or function. FORTRAN does not have any reserved words - the compiler recognizes keywords in context. For reasons of clarity and readability though, users are recommended to use names that are distinct from those of FORTRAN. Examples of Valid FORTRAN Names XPos Eatup FilSet MAXO L5 Shell Bubble Examples of Invalid FORTRAN Names 2ndTime Begins with digit TooLarge More than six characters No Good Non-alphanumeric character FORTRAN Reference Manual Page 23 FORTRAN Names, Arrays, and Substrings 4.1.1 Chapter 4 Scope of FORTRAN Names The scope of a FORTRAN name is that region of a program over which the name is known or can be referenced. In general, the scope of a name is either local to a program unit or global to the entire FORTRAN program. There are certain exceptions which are described later. A name with global scope can be used in more than one program unit (subroutine, function or the main program) and still refer to the same object. Names with global scope can only be used in a single, consistent manner within the same program. The names of all subroutine, function and block-data program units, the names of common areas, and the program name, have global scope. Therefore, there cannot be a subroutine program unit that has the same name as a function program unit or a common ~rea. Similarly, two function program units cannot have the same name. A name with local scope is only known within a single program unit. A name with local scope can therefore be used in other program units with the same or different meanings everywhere it is used. Within a specific local scope, a name must be used consistently and refer to the same objecte The names of variables, arrays, constants, arguments and statement-functions all have local scope. A name with local scope can be used in the same compilation- as the same name with global scope as long as the global name is not referenced within the program unit containing the local name. For example, there can be a function called PARTY, and a local variable called PARTY in another program unit, as long as the program unit containing the variable called PARTY does not try to reference the function called PARTY. The FORTRAN compiler detects all such scope errors and issues diagnostics concerning them. Common block names are an exception to the scope rules. It is possible to refer to a globally scoped common block name in a program unit containing a locally scoped name identical to that of the common block. This situation is allowed because common block names always appear in slashes, such as /COLD/, and therefore the compiler can always distinguish such names. Formal arguments to statement-functions are another exception to the scope rules. The scope of formal arguments of statementfunctions is the body of the statement function itself. Any other use of those names in the statement-function is not allowed and neither is any other use of such names outside the statement-function. For example, if a formal argument to a statement-function has the same name as that of a function subprogram, that function subprogram may not be referenced from within the body of the statement-function. References to formal argument names of a statement-function from outside the body of the statement-function refer to objects which are different from the arguments of the statement-function. Page 24 FORTRAN Reference Manual Chapter 4 FORTRAN Names, Arrays, and Substrings Names used as implied-DO control variables in DATA statements and input-output statements have a scope which is local to the DATA statement or input-output statement. 4.1.2 Undeclared FORTRAN Names When a user name that has not previously appeared in a program unit is referenced in an executable statement, FORTRAN decides how to classify that name from the context in which it appears. If the name appears to be a variable, FORTRAN creates a symboltable entry for that name. Its type is inferred from the first letter of the name. Variables starting with the letters I, J, K, L, M and N are considered to be of type integer; all others are considered to be of type. real. If an undeclared name appears in the context of a function reference, the function's type is inferred from its name in the same manner as for variables. In both cases, these default type rules can be overridden by previous IMPLICIT statements (see the chapter on "Specification Statements"). Similarly, a name appearing in the context of a subroutine call has an entry created for it. If a symbol table entry exists for a subroutine or function name, its attributes are coordinated with those of the newly created entry. Inconsistencies such as a subroutine name used in the context of a function or vice versa give rise to error diagnostics. In general, users are encouraged to declare all names used in each program unit, since it helps to assure that FORTRAN associates the proper definition with the name. Letting FORTRAN decide on the default can sometimes result in logical errors that are hard to find, usually at execution time when strange results or forms of behavior are exhibited. 4.2 Array Declarations Arrays provide the means to deal with data aggregates where the elements of the aggregates are homogeneous. An array declaration specifies a symbolic name that identifies an array in a program unit. The declaration also serves to specify properties of the array, such as its dimension and, optionally, the type of its elements. In any given program unit only one array declaration is allowed for any given array - duplicate declarations are flagged as errors. The form of an array declaration is: array name (dim [, dim] ••• Each 'dim' above is a dimension declarator as defined below. The number of dimensions for an array is equal to the number of dimension declarations given when the array is declared. FORTRAN Reference Manual Page 25 Chapter 4 FORTRAN Names, Arrays, and Substrings 4.2.1 Dimension Declarations A dimension declarator serves to define the bounds of a specific dimension in an array. FORTRAN-11 provides for defining both the lower and the upper bound of a dimension. The form of a dimension declaration is: [lower bound :] upper bound The optional lower bound, and the upper bound are arithmetic expressions, called dimension bound expressions, in which all constants, symbolic constant names, and varIables are of type integer. The upper bound of the last dimension declaration can be an asterisk (see 'assumed size arrays', later). A dimension bound expression must not contain any function or array element references. Integer variables can appear in dimension bound expressions only in adjustable array declarations (see 'adjustable arrays', later). If a symbo~ic constant name or variable in a dimension bound expression is not of default implied integer type, it must be specified as integer via a type statement or an IMPLICIT statement before its use in a dimension bound expression. Either dimension bound may have a positive, negative or zero value. The upper bound must not be less than the lower bound. If only the upper bound is specified, the lower bound has the value one (1). An upper bound of • is always greater than or equal to the lower bound~ 4.2.2 Kinds of Array Declarations There are three basic forms of array declarations. A constant array declaration is one in which all the bound expressions are integer constant expressions. dimension An adjustable array declaration is one in which the dimension bounds contain integer variables. Adjustable arrays may be used as dummy arguments in subroutines and functions. Variables which define the bounds of adjustable arrays must either be formal arguments themselves, or they must be in common blocks. An assumed size array declaration is one in which the upper bound of the last dimension is an asterisk character '.'. Assumed size arrays may also only be used as dummy arguments to subroutines and functions. Using assumed size arrays in procedures circumvents any range checking which the FORTRAN system can perform. Page 26 FORTRAN Reference Manual FORTRAN Names, Arrays, and Substrings Chapter 4 4.2.3 Actual Arrays and Dummy Arrays An actual array declarator "actually" declares an array there and then. Each actual array declarator must be a constant array declarator as defined above. An actual array declarator can be used in the type statement, the DIMENSION statement and the COMMON statement, as defined in the chapter on "Specification Statements". A dummy array declarator defines a dummy argument for a subroutine or function. A dummy array declarator can be any of the forms given above: constant, adjustable or assumed size. A dummy array declarator can only appear in subroutines and functions. A dummy array declarator may not appear in a COMMON statement. Examples of Array Declarations ** * C C C C C ** * * * * 4.2.4 Constant array Declarations in type statements a 100 element vector with bounds 1 - 100 INTEGER VECTOR(lOO) a 20 element matrix with 5 rows and 4 columns REAL MATRIX(S, 4) a 256 element array with bounds 0 - 2S5 CHARACTER~2 CHARS(O : 255) a 3 element array LOGICAL*2 BOOLS(-l : +1) a constant expression dimension REAL WOOD (2*4) Adjustable Array Declaration in a DIMENSION statement DIMENSION SCREEN(l : CHARS, 1 : LINES) Assumed size array declaration in a type statement. REAL VARIAB(5, *) Referencing Array Elements - Array Subscripts An array sUbscrirt is the means to reference an element of array. The form 0 an array subscript is: (subexpr [, subexpr] the ••• ) Note that the term "subscript" includes enclose the subscript expression list. the parentheses that A subscript expression is an integer expression. A subscript expression can contain array element references and function FORTRAN Reference Manual Page 27 FORTRAN Names, Arrays, and Substrings Chapter 4 references. If a subscript expression contains a function reference, the function must not change the value of any other subscript expression in the same subscript. In any given program unit, the value of each subscript expression should not be less than the lower bound for the dimension and should not be greater than the upper bound for the dimension. If the upper dimension bound is an asterisk, the subscript expression must not be greater than the size of the dummy array. Examples of Arrays with Subscripts SCREEN (2, 3) VARIAB(N+l, MAX(3, 4» 4.2.5 Using Unsubscripted Array Names Generally speaking, array names must be followed by subscripts. There are some exceptions where the array name alone can be used. An unsubscripted array name can be used in the following places: a list of dummy arguments for a subroutine or function program unit, a COMMON statement when declaring that the that common block, array resides in a type statement when the type of the array is established, an array declaration when the array dimensions are being established, an EQUIVALENCE statement, a DATA statement, the list of actual arguments in a procedure, reference to an the list of an input-output statement if the array is assumed size dummy array, external not an a unit identifier for an internal file in an input-output statement if the array is not an assumed size dummy array, the format identifier in an input-output array is not an assumed size dummy array, Page 28 statement if the FORTRAN Reference Manual FORTRAN Names, Arrays, and Substrings Chapter 4 a SAVE statement. 4.3 Character Substrings A Character Substring is a contiguous portion of a character object. The type of a character substring is of type CHARACTER. A character substring can be identified by a symbolic name, and The it can be referenced and assigned values by that name. forms of a substring ~ are: character variable([start) : [finish)) where 'start' and 'finish' are substring expressions. A character variable may be an element of a character array. 'start' specifies the leftmost character position of the substring. 'finish' specifies the rightmost character position of the substring. The values of 'start' and 'finish' must be such that: 1 <= start <= finish <= length where 'length' is the length of the character variable or character array element. If 'start' is omitted, the value one (l) is used. If 'finish' is omitted, the value 'length' is used. Both 'start' and 'finish' can be omitted. In such a case, a substring reference of the form s(:) is equivalent to s. The length of a character substring is 'finish' - 'start' + 1. A substring expression is any integer expression which can contain array element references, and function references. The same restrictions (with regard to side effects) apply to substring expressions as apply to array subscripts. Examples of Character Substrings ROPEY(1:3) THELOT(:) ACHAR(5:5) FOURCH(:4) FORTRAN Reference Manual Page 29 FORTRAN Names, Arrays, and Substrings Paqe 30 Chapter 4 FORTRAN Reference Manual Expressions Chapter 5 Chapter 5 - Bxpressions This chapter describes the rules for expressions. An expression is formed from operands, operators, and parentheses. FORTRAN has four classes of expressions: • Arithmetic expressions, • Character expressions, • Relational expressions, Logical expressions. 5.1 Arithmetic Expressions An arithmetic expression expresses a generates a numeric value. 5.1.1 numeric computation and Arithmetic Operators The arithmetic operators are as follows: +----------+-------------------------+ I Operator I Meaning I +----------+-------------------------+ ** Exponentiation I Division Multiplication Subtraction or Negation Addition or Identity * + +----------+-------------------------+ The **, I, and operators can be * operators are binary operators. u~ary The + and or binary operators. The ** operator has the highest precedence, then the * and I operators, and lastly the + and - operators. Parentheses may be used freely to change the order of evaluation. FORTRAN Reference Manual Page 31 Chapter 5 Expressions 5.1.2 Arithmetic Operands An arithmetic operand consists of a primary, a factor, a term or an arithmetic expression. These various kinds of operands are discussed below. The primary operands are: • • • • • Unsigned arithmetic constant, Symbolic name of an arithmetic constant, Arithmetic variable reference, Arithmetic array element reference, Arithmetic function reference, Arithmetic expression enclosed in parentheses. The factor operands are: • Primary, • Primary ** factor. A factor is formed from a sequence of one or more primaries separated by an exponentiation operator. The second form means that an expression such as: 2**3**4 is to be interpreted as: 2** (3**4) A term operand is: • Factor, • Term I factor, • Term * factor. A term is formed from one or more factors separated by the multiply or divide operator. Factors are combined left to right. An arithmetic expression consists of: • • • • Term, +term or -term, Arithmetic expression + term, Arithmetic expression - term. An arithmetic expression consists of a series of terms separated by plus or minus operators. The first term in an expression can be preceded by a plus or minus sign. Terms are combined left to right. Note that the rules for expressions mean that two consecutive operators form an incorrect expression. Thus A**-B is wrong, whereas A**(-B) is correct. Page 32 FORTRAN Reference Manual Expressions Chapter 5 5.1.3 constant Expressions Constant expressions are used in many language constructs throughout FORTRAN, especially in specification statements. There are two forms of constant expressions, namely arithmetic constant expressions and integer constant expressions. These are discussed below. An arithmetic constant expression is an expression in which each primary is an arithmetic constant, the symbolic name of an arithmetic constant or a constant expression enclosed in parentheses. Exponentiation is only allowed if the exponent is of type integer. Examples of Arithmetic Constant Expressions 5.0*2 2**31-1 2*(4.5, 9.8) -16/4 3.141592/2 5**(3+2) An integer constant expression is an arithmetic expression in which each constant is of type integer. constant Examples of Integer Constant Expressions 3*5 5.1.4 -10 4+5*(9-2) Type Conversion Rules for Arithmetic Expressions The data type of an expression is ultimately derived from the data types of its operands according to the rules stated below. When operands of mixed data types appear in an expression, FORTRAN performs implicit type conversion on the operands according to well-defined rules in order to generate the result. When the plus "+" operator or the minus "-" operator operate upon a single operand (they are used as unary operators), the data type of the result is the same as the data type of the operand. When an arithmetic operator applies to a pair of operands, the type of the results is as shown in the tables below. The letter I stands for an operand or result of type Integer, the letter R for Real, the letter D for Double-precision and the letter C for Complex. The rules are given in the form of assignments. The result type is indicated by the letter to the left of the equals sign and the derivation of that result is given by the expression to the right of the equals sign. The function names REAL, DBLE FORTRAN Reference Manual Page 33 Chapter 5 Expressions and CMPLX are as defined in the table of intrinsic the Appendix on "Intrinsic Functions". 5.1.4.1 functions in Rules for Add, Subtract, Multiply and Divide The two tables below define the types and interpretations the +, -, * and I operators. For example, to obtain the rule Il.C2 where 'II' is an integer and 'C2' is a complex, look in second part of the table; find the 'II' entry under 'Xl' the 'C2' entry across from 'X2', the rule is then: for for the and 'C • CMPLX(REAL(Il), 0.0) + C2' which is interpreted as: 'the result is of type complex; the first operand is obtained by converting the integer to a real, then converting that to a complex with the imaginary part 0.0; the two complex numbers are then added'. The rules for subtraction, multiplication and division are obtained by replacing the "+" signs with the desired operator. +------+-----------------------------+-----------------------+ XlX2 12 R2 +------+-----------------------------+-----------------------+ 11 I • 11 + 12 R • REAL(Il) + R2 Rl R = Rl + REAL(I2) R = Rl + R2 Dl 0 = 01 + OBLE(I2) 0 • 01 + OBLE(R2) Cl C = C1+CMPLX(REAL(I2), 0.0) C = C1+CMPLX(R2, 0.0) +------+-----------------------------+-----------------------+ I I I I +------+---------------------+-------------------------------+ XlX2 02 C2 +------+---------------------+-------------------------------+ 11 0 a OBLE(Il) + 02 C = CMPLX(REAL(Il), 0.0)+C2 Rl 0 = OBLE(Rl) + 02 C • CMPLX(R1, 0.0)+C2 Dl 0 = 01 + 02 Not Allowed C1 Not Allowed C a Cl+C2 +------+---------------------+-------------------------------+ I 5.1.4.2 I I Rules for Exponentiation Operator The tables below define the expressions of the form Xl**X2. Page 34 I types and interpretations for FORTRAN Reference Manual Expressions Chapter 5 +------+-----------------------------+--------------------------+ X2 I I X1 I 12 I R2 +------+-----------------------------+--------------------------+ 11 I - 11 ** 12 R REAL (11) ** R2 Rl Dl Cl R·· Rl ** 12 D • Dl ** 12 C - Cl**I2 R • Rl ** R2 D = Dl ** DBLE(R2) C • Cl**CMPLX(R2, 0.0) +------+-----------------------------+--------------------------+ +------+----------------------+---------------------------------+ I X1X2 I I D2 C2 I +------+----------------------+---------------------------------+ 11 D = DBLE(Il) ** 02 C = CMPLX(REAL(Il), O.0)**C2 Rl Dl Cl D • DBLE(R1) ** 02 0 01 ** D2 Not Allowed = C = CMPLX(Rl, 0.0)**C2 Not Allowed C = Cl**C2 +------+----------------------+---------------------------------+ Four of the entries in the above table specify what happens when a complex argument is raised to a complex power. In these cases, the value of the expression is the principal value, determined by the formula: Xl**X2 = EXP(X2 * LOG(X2» where EXP and LOG are the exponential and natural logarithm intrinsics described in the chapter on "Program Structure". Except for values raised to an integer power, in mixed mode expressions, the operand which differs from the type of the result is converted to the type of the result according to the rules given in the tables above. The operator then operates on a pair of operands of the same type. When a primary is raised to an integer power, the integer does not need to be converted. 5.1.5 Coercion Rules for Integers of Different Size In expressions involving INTEGER*l, INTEGER*2 and INTEGER*4 (INTEGER), the smaller sized operand is always "promoted" to the size of the larger operand, and the arithmetic operation is performed in the larger sized field. In all cases, elements of type INTEGER*l are always promoted to INTEGER*2. In any case, assigning the result of an expression to a variable of smaller size produces an undefined result if the value stored exceeds the range of values allowed for that specific variable. Note also that many FORTRAN statements and functions specifically require arguments of type INTEGER. In such cases, neither arguments of size INTEGER*l nor INTEGER*2 may be used. FORTRAN Reference Manual Page 35 Chapter 5 Expressions 5.1.6 Integer Division If an integer operand is divided by another integer operand, the result is not the strict mathematical quotient. Instead, the quotient is obtained by truncating towards zero. Thus 1/2 is 0 and (-a)/3 is -2. 5.2 Character Expressions ~ character expression operates on character strings and generates character values. The simplest form of character expressions are: • • • • • • Character Character Character Character Character Character constant, variable, array element reference, substring reference, function reference, expression enclosed in parentheses. There is only one character operator - the concatenation. "II" sign, meaning The result of a character concatenation operations such as: II Xl X2 is a value which is 'Xl' concatenated on the right with 'X2'. The length of the result is the sum of the lengths of the individual operands. 5.2.1 Restrictions on the use of String Expressions Formal arguments to procedures can be character strings whose length is specified as (*). This designates the string as an assumed size character string whose length is determined at the time an actual string argument is associated with that formal argument. ~ character string expression involving concatenation of such a string argument may not be passed as an actual argument to any procedure, nor may it appear in the format specification of an input-output statement, nor may it appear as an item in the 'iolist' of an input-output statement. Example of String Concatenation 'Left Side' II 'Right Side' Page 36 FORTRAN Reference Manual Expressions Chapter 5 5.3 Relational Expressions Relational expressions compare arithmetic expression values or character expression values. Relational expressions yield logical values. The relational operators are: +----------+--------------------------+ I Operator I Meaning I +----------+--------------------------+ .LT. Less than .LE. .EO. .NE. .GT. .GE. Less than or equal to Equal to Not equal to Greater than Greater than or equal to +----------+--------------------------+ 5.3.1 Arithmetic Relational Expressions An arithmetic relational expression expresses a relationship between arithmetic operands. The form of an arithmetic relational expression is; El relop E2 where 'El' and 'E2' are arithmetic operands, and 'relop' is of the operators selected from the table above. one Only the .EO. (equality) and .NE. (inequality) allowed for operands of complex type. are operators If the operands are of different types, the relational sion is treated as if it were in the form: «El) - (E2» expres- relop 0 where 0 (zero) is the same type as the expression. Comparison of a double precision value and a complex not allowed. 5.3.2 value is Character Relational Expressions A character relational expression is of the form: El relop E2 where 'El' and 'E2' are character expressions and 'relop' is one of the relational operators selected from the table above. The order ing of character .expressions is as defined in the ASCII character set table in the appendices. The .EO. (equality) and FORTRAN Reference Manual Page 37 Chapter 5 Expressions .NE. (inequality) operators do not use the ordering. If the operands in a character relational expression are of different lengths, the shorter operand is considered to be padded on the right with spaces until the operands are of the same length. 5.4 Logical Expressions A logical expression operates on values of type logical and generates a result of type logical. The simplest forms of logical expressions are: Logical constant, Logical variable reference, Logical array element reference, Logical function reference, Relational expression. • • • • Other logical expressions are built up from these simple by using parentheses and the logical operators as follows: forms +----------+------------------------+ I Operator I Meaning I +----------+------------------------+ .NOT. Logical Negation .AND. oOR. .EOV. .NEOV. Logical Conjunction Inclusive Disjunction Logical Equivalence Logical Nonequivalence +----------+------------------------+ 5.4.1 Precedence of Logical Operators The precedence of the logical operators is shown page: on the next +-----------------+------------+ I Operator I Precedence I +-----------------+------------+ .NOT. Highest .AND • • OR • • EOV. or .NEOV. Lowest +-----------------+------------+ The .AND. and .OR. operators are binary operators and must appear between their operands. The .NOT. operator is a unary operator and appears before its operand. Operators of equal precedence associate left to right. Page 38 FORTRAN Reference Manual Expressions Chapter S A .AND. B .AND. C is equivalent to: (A .AND. B) .AND. C .NOT. A .OR. B .AND. C is equivalent to: ( • NOT. A) • OR. Two .NOT. operators must not appear The expression: (B • AND. C) adjacent to each other. A .AND. .NOT. B is an example of an allowable expression with two adjacent operators. 5.S Precedence of Operators When arithmetic, relational and logical operators appear in the same expression, their relative precedence is: +------------+--------------+ I Operator I Precedence I +------------+--------------+ Arithmetic I Highest I I +------------+--------------+ Rel~tional Logical 5.6 Intermediate Lowest Evaluation Rules and Restrictions for Expressions Any variable, array element or function referenced in an expression must be defined at the time it is referenced. Integer variables must be defined with an arithmetic value rather than a statement label set by an ASSIGN statement. If a character string or substring is referenced in an expression, all the referenced characters should be defined at the time of the reference. It is an error to divide by zero. It is also an error to raise a zero value to a zero or negative power. It is also an error to raise a negative value to a real or double precision power. FORTRAN Reference Manual Page 39 Expressions 5.6.1 Chapter 5 Restrictions on Function References In any given statement, it is an error if a function reference within that statement changes any other object in the statement. If a function reference causes an actual argument to the function to become defined, it is an error to reference that object anywhere else in the statement containing the function reference. Page 40 FORTRAN Reference Manual Specification Statements Chapter 6 Chapter 6 - Specification Statements This chapter describes SVS FORTRAN specification statements. Specification statements are non-executable. They are used to define properties of user-defined variables, arrays and functions. There are nine types of specification statements: • • • • • • • • • Type statements, DIMENSION statements, COMMON statements, PARAMETER statements, IMPLICIT statements, EXTERNAL statements, INTRINSIC statements, SAVE statements, EQUIVALENCE statements. Specification statements must precede all executable statements in a subprogram unit. If any IMPLICIT statements appear in the subprogram, ,they must precede all other specification statements. Other than that, specification statements can appear in any order within their own group. 6.1 Type Statements - Declaring Data Types !YP! statements specify the data type of user-defined names. A type statement either confirms or overrides the default type rules for names. Type statements can also convey dimension information when declaring arrays. A user-defined name for a variable, array, formal argu~ent, external function or statement-function can appear 1n a type statement. Such an appearance defines the type of that name for the entire program uni~ that contains the type statement. In any given program unit, a user-defined name may only appear once in a type statement •. A type statement can confirm the type of an intrinsic function, but it is not required to do so. A main program name or a subroutine name must not appear in a type statement. A type statement can define the dimensions of an array, or the dimensions can be declared in a DIMENSION statement (see below), independently of the type statement. FORTRAN Reference Manual Page 41 Specification Statements 6.1.1 Chapter 6 Arithmetic Type Statements Arithmetic type statements are used to declare arithmetic objects. The form of an arithmetic type statement is: type var [, var J •• data 0 is one of INTEGER, INTEGER*l, INTEGER*2, INTEGER*4, REAL, REAL*4, REAL*8, DOUBLE PRECISION or COMPLEX. 'type' INTEGER and INTEGER*4 are the same. REAL and REAL*4 are the same. DOUBLE PRECISION and REAL*8 are the same. evart is a variable name, array name, formal argument name, function name or array declarator. See the definition of array declarators in the chapter on "FORTRAN Names, Arrays and Substrings". Examples of Arithmetic !r2! Statements C declare some integer variables. C INTEGER CLOCK, HANDS(2), TIME(24) C C declare some real and double precision variables. C REAL RADIO, K10l, VARBLS(lO, 10, 5) DOUBLE PRECISION TWOS(50), TWICE, SECOND C C declare some complex data items C COMPLEX 6.1.2 FUNKS, ROCK, BACH(48) CHARACTER Type Statement The character type statement is used to declare CHARACTER data objects. The form of a CHARACTER type statement is: CHARACTER [*nnn [,1] var [*nnn] [, var [*nnn] J ••• 'var' is a variable name, array name, formal argument name or an array declarator. For a definition of an array declarator, see the chapter on "FORTRAN Names, Arrays and Substrings". 'nnn' is the length, in characters, of a character variable or character array element. The length Page 42 FORTRAN Reference Manual Specification Statements Chapter 6 must be an unsigned integer in the range 1 to 255 or a constant expression enclosed in parentheses, whose value lies in the range 1 to 255. The length can also be specified as (*), when the name is being defined either as a formal argument which is an assumed size character string, or for the purpose of establishing a type for later use in a PARAMETER statement. The length 'nnn', following the type name CHARACTER, is the default length for any name in the list that does not have its length specified explicitly. In the absence of a length specification, the default length is one (1). A length immediately following a variable or array element overrides the default length for that item only. For an array, the length specifies the length of each element of that array. A formal argument defined as CHARACTER*(*) cannot be used as an actual argument to a procedure if it is concatenated in a character string expression, whereas a symbolic name of a constant can be used in such a place. Examples of CHARACTER !YE! Statements CHARACTER FLIP*lO, FLOP*20 CHARACTER WILD(15)*20 CHARACTER*80 LINE(24) CHARACTER*(lO*20) LSTR CHARACTER* (*) VARBLE 6.1.3 LOGICAL Type Statement The logical type statement is used to declare objects. The form of a LOGICAL type statement is: type 'type' logical data var [, var] is one of LOGICAL, LOGICAL*l, LOGICAL*2 or CAL*4. LOGI- LOGICAL is the same as LOGICAL*4. evart is a variable name, array name, formal argument name, function name, or an array declarator. For a definition of an array declarator, see the chapter on "FORTRAN Names, Arrays and Substrings". FORTRAN Reference Manual Page 43 Chapter 6 Specification Statements Examples of LOGICAL !Ie! Declarations LOGICAL LOGICAL*2 LOGICAL' 6.2 SONG BLACK, WHITE YES (lO) , NO(lO) DIMENSION - Declare Data Dimension A DIMENSION statement specifies the number of dimensions user-defined array. The form of a DIMENSION statement is: DIMENSION of a var (dim) [, var (dim)] ••• where each one of the 'var(dim)' pairs is an array declarator the form: of name (d [, d ] ••• ) 'name' is the user-defined name of the array, 'd' is a dimension declarator. 6.2.1 Dimension Declarators The number of dimensions in the array is the number of d~men sion declarators in the array declarator. The maximum number of dimensions is seven. The rules for array and dimension declarators are defined in the chapter on "FORTRAN Names, Arrays and Substrings". Examples of DIMENSION Statements 6.3 DIMENSION forth(lO, 5:15, 0:99) DIMENSION axis(6) COMMON - Declare a COMMON Block Common blocks provide a means to share variables between multiple independently-compiled program units. Common blocks and their contents are defined via the COMMON statement. The form of the COMMON statement is: COMMON [/[cname]/] nlist [[,] /[cname]/ nlist] ••• Page 44 FORTRAN Reference Manual Specification Statements Chapter 6 'cname' is a common block name. If any 'cname' is ted, the blank common block is implied. omit- 'nlist' is a list of variable names, array names and array declarators, all separated by commas. Formal argument names and function names must not appear in a COMMON statement. In each COMMON statement, all variables and arrays appearing in each 'nlist', following a common block name, are declared to be in that common block. If the 'cname' is omitted, all elements appearing in the 'nlist' are specified to be in the blank common block. Any common block name can appear more than once in COMMON statements in the same subprogram unit. All elements in all 'nlists' for the same common block are allocated storage, sequentially in that common block, in the order of their declaration. All elements in a single common area must be all of type acter or none of type character. char- The size of a common block is equal to the number of bytes of storage needed to hold all elements in that common block. If the same named common block is referenced in several subprogram units, the size must be the same in all those units. Examples of COMMON Statements COMMON 6.4 /horde/ TOKEN(lOO), SYMBOL (lOO) PARAMETER - Make a Symbolic Association A PARAMETER statement associates a symbolic name with a constant value. That constant is thereafter associated with that symbolic name, such that using the name is synonymous with a use of the constant. The form of a PARAMETER statement is: PARAMETER (name=expr (,name=expr] ••• ) 'name" is the symbolic name to be defined, 'expr' is an expression that is to be associated with the name. The expression noted in the definition above must be a constant expression. FORTRAN Reference Manual Page 45 Chapter 6 Specification Statements Examples of PARAMETER Statements C 6.5 PARAMETER (TODAY PARAMETER (BASE = 'FRIDAY') s 1, LIMIT = 100) IMPLICIT - Establish Default Data Type FORTRAN normally assigns a default type to a variable depending on the first letter of that variable. The IMPLICIT statement overrides the default type rules and establishes a new default type for variables. The form of the IMPLICIT statement is: IMPLICIT type (letter-list) [,' type (letter-list)] ••• 'type' is one of the data types: INTEGER, INTEGER·l, INTEGER*2, INTEGER*4, REAL, REAL*4, REAL*B, LOGICAL, LOGICAL*l, LOGICAL*2, LOGICAL*4, DOUBLE PRECISION, COMPLEX or CHARACTER[*nnn] 'letter-list' is a list of single letters or ranges of letters. A range of letters is indicated by the first and last letters in the range, separated by a minus sign. If a range is specified, the letters must be in alphabetical order. 'nnn' is only applicable to a character data type, and is the size of the character type that is to be associated with that letter or letters. 'nnn' must be an unsigned integer in the range 1 thru 255. If 'nnn' is not specified, a value of one (1) is assumed. An IMPLICIT statement defines the type and size for all userdefined names that begin with the letter or letters appearing in the specification. An IMPLICIT statement only applies to the program unit in which it appears. IMPLICIT statements do not change the type of any intrinsic functions. Implicit types can be overridden or confirmed for any specific user-defined name if that name appears in a subsequent type statement. An explicit type in a FUNCTION statement also takes precedence over an IMPLICIT statement. If the type in question is a character type, the length is also overridden by any later type specification. A program unit can have more than one IMPLICIT statement, but all IMPLICIT statements must precede all other specification statements. Page 46 FORTRAN Reference Manual Specification Statements Chapter 6 Examples of IMPLICIT Statements * * ** * * ** * 6.6 declare all names beginning with A as integer. IMPLICIT INTEGER (A) declare all names starting with the letters 0, X, Y or Z to be complex. IMPLICIT COMPLEX (0, X-Z) declare all names starting with C as CHARACTER. IMPLICIT CHARACTER*255 (C) EXTERNAL - Declare External or Dummy Procedure An EXTERNAL statement specifies that a user-defined name is the name of an external procedure or a dummy procedure. It also allows such a name to be used as an actual argument to a subroutine or function reference. The form of an EXTERNAL statement is: EXTERNAL proc-name [, proc-name] ••• where each 'proc-name' is the name of an external procedure, dummy procedure or block data subprogram. A name appearing in an EXTERNAL statement declares that name to be an external procedure. Statement-function names must not appear in an EXTERNAL ment. state- If an intrinsic function name appears in an EXTERNAL statement, that name becomes the name of an external procedure and the corresponding intrinsic function can no longer be called from that program unit. A user-defined name can only appear once in an EXTERNAL ment. 6.7 state- INTRINSIC - Declare Intrinsic Function An INTRINSIC statement declares that a name is an intrinsic function. It also allows a specific intrinsic function name to be used as an actual argument to a subroutine or function reference. The form of an INTRINSIC statement is: INTRINSIC name [, name] FORTRAN Reference Manual Page 47 Specification Statements Chapter 6 where 'name' is an intrinsic function name. An intrinsic function is anyone of a specific set of predefined functions in the FORTRAN language, such as SIN or MAX. Since these names are in no way reserved, user functions as well as variables can have the same name as an intrinsic function, but not in the same scope. The intrinsic statement, though normally not required, is used to specifically state that the name in question refers to an intrinsic function. Each name may appear only once in an INTRINSIC statement. If a name appears in an INTRINSIC statement, it may not appear in an EXTERNAL statement. All names used in an INTRINSIC statement must be system-defined intrinsic functions. For a list of intrinsic functions, see the Appendix on "Intrinsic Functions". If a specific name of an intrinsic function is used as an actual argument in a program unit, that name must be declared in an INTRINSIC statement in that program unit. If a generic function name appears in an INTRINSIC that function still retains its generic properties. statement, In a given program unit, a name must not appear one INTRINSIC statement. more Certain intrinsic functions may not be ments. These are: used as in than actual argu- The type-conversion functions: INT, IFIX, IDINT, FLOAT, REAL, DBLE, CMPLX, ICHAR and CHAR. SNGL, The lexical relationship functions: LGE, LGT, LLE and LLT. The functions for choosing largest or smallest values: MAX, MAXO, AMAXl, DMAXl, AMAXO, MAXl, MIN, MINO, AMINl, DMINl, AMINO and MINl. 6.8 SAVE - Retain Definition Status A SAVE statement is used to retain the definition of a program object after returning from the procedure which defines that program object. Within a subroutine or function subprogram, a program object specified in a SAVE statement remains defined after exit from the subroutine or function. The form of a SAVE statement is: SAVE [thing [, thing] ••• ] where 'thing' is a common Page 48 block name enclosed in slashes, a FORTRAN Reference Manual Specification Statements Chapter 6 variable name or an array name. Any given name may only appear once in a SAVE statement. The names of dummy arguments, procedures and objects appearing in common blocks must not appear in a SAVE statement. If a SAVE statement appears without an associated list of program objects, it is the same as if all objects in that program unit which could appear in the SAVE statement actually had appeared in the SAVE statement. Specifying a as saving all mentioned in a ment in every SAVE statement optional. common block name in a SAVE statement is the same the elements in that common block. A common block SAVE statement must be mentioned in a SAVE statesubprogram in which that common block appears. A has no effect in the main program, and is Examples of SAVE Statements C C Save everything in the subprogram with C SAVE C C Save some variables C SAVE dimes, nickels, pennies C C Save all of common blocks C SAVE 6.9 /Stamps/, /Lettrs/ EQUIVALENCE - Share Storage Between Elements An EQUIVALENCE statement specifies that two or more variables or arrays are to share the same storage. If the shared variables are of different types, the EQUIVALENCE statement does not cause any kind of automatic type conversion. The form of an EQUIVALENCE statement is: EQUIVALENCE where 'nlist' (nlist) [, (nlist) ] is a list of at least two variable names, array names, array element names or character substring names. Argument names must not appear in EQUIVALENCE statements. Subscripts must be integer constant expressions and must be within the bounds of the array that they reference. FORTRAN Reference Manual Page 49 Chapter 6 Specification Statements An EQUIVALENCE statement specifies that the storage sequences of the elements that appear in the list 'nlist' have the same first storage location. Two or more variables are said to be associated if they refer to the same actual storage. Thus an EQUIVALENCE statement causes its list of variables to become associated. If an array name appears in an EQUIVALENCE list, it refers to the first element of the array. 6.9.1 Restrictions on EQUIVALENCE Statements An EQUIVALENCE statement must not specify that the same storage location is to appear more than once. For example: REAL R, S (10) EQUIVALENCE (R, S(l», (R, S(5» is in error because it forces the variable "R" to appear distinct memory locations, namely at S(l) and S(5). in two An EQUIVALENCE statement must not specify that consecutive array elements be stored out of sequential order. For example: REAL R(lO), S(lO) EQUIVALENCE (R(l), S(l», (R(5), S(6» is in error because, having defined R(l) and S(l) to be associated, the statement then attempts to define R(5) and S(6) to be associated, and this means that the array "R" has somehow been "stretched". Names of dummy arguments must not appear in an EQUIVALENCE statement. Also, if a variable name is also a function name, that name must not appear in an EQUIVALENCE statement. When EQUIVALENCE statements and COMMON statements are used together, there are further restrictions. An EQUIVALENCE statement must not try to associate storage elements in different common blocks. An EQUIVALENCE statement can extend a common block by adding storage elements following the common block, but not preceding the common block •. For example: COMMON /MASSES/ R(lO) REAL S(lO) EQUIVALENCE (R(l), S(lO» is in error because it tries to extend the common block by adding storage before the start of the block. That is, when R(l) and S(10) are associated, it means that S(l) would be nine locations before the defined start of the block. Page 50 FORTRAN Reference Manual Chapter 7 Data Initialization Chapter 1 - Data Initialization The DATA statement is used to (statically) initialize data variables. The DATA statement is non-executable in the sense that the compiler does not generate any code for it. If a DATA statement is present within a subprogram, it may appear anywhere after the specification statements (if there are any). The form of a DATA statement is: DATA nlist /clist/ [[,] nlist /clist/] enlist' is a list of variables, arrays, array element names, substring names and implied-DO lists. 'clist' is a list of constants, or constants preceded by an integer-constant repeat-factor and an asterisk. Examples of repeated data items are: 5*3.14159 3*'Help' 100*0 There must be the same number of values in each 'clist' as there are variables or array elements in the corresponding enlist'. The appearance of an array in an enlist' is equivalent to a list of all the elements in that array in order of storage sequence. Array elements and substrings may be indexed by integer constant expressions (but see the implied-DO loop below). The type of each element in a 'clist' must be the same as the type of the corresponding variable or array element in the accompanying enlist'. If necessary, the 'clist' constant is converted to the type of the enlist' object according to the rules for arithmetic conversion given in the table in the chapter on -Assignment Statements-. A DATA statement can be used to initialize any variable, element or substring that is ~ one of the following: array a dummy argument, an object in blank common or any object with an object in blank common, FORT~N Reference Manual which is associated Page 5L Data Initialization Chapter 7 a variable in a function subprogram whose name is also the same name as that of the function or one of its alternate entry-point names. Objects may only be initialized once in any given program unit. DATA statements in BLOCK DATA subprograms may objects in named COMMON areas. only initialize Examples of DATA Statements ** * Declare some variables * * initialize some reals * ** ** * ** * 7.1 REAL FIRST, SECOND INTEGER NIG, NOG COMPLEX WEIRD(lO) DOUBLE PRECISION VECT(5) DATA FIRST, SECOND /1.0, 2.0/ initialize some integers DATA NIG /10/, NOG /20/ initialize two elements of the complex array DATA WEIRD(2), WEIRD(5) /2 * (0.0,0.0)/ initialize all the double precision array DATA VECT /0.0, 0.0, 0.0, 0.0, 0.0/ Initializing Character Variables If an 'nlist' item is of type character, the corresponding 'clist' item must be a character constant expression. If the 'clist' item is shorter than the length of the 'nlist' item, the initial characters occupy the leftmost positions of the character data item and the remaining character positions are filled with spaces. If the 'clist' item is longer than its corresponding 'nlist' variable, only the characters needed to initialize the 'nlist' item are used and the remaining characters are ignored. Page 52 FORTRAN Reference Manual Chapter 7 Data Initialization Examples of Character Initialization DATA STRING DATA SVECT /'Old Rope'/ /6 * 'Attached'/ The second example assumes that SVECT is a 6 element array. 7.2 character Initializing Non CHARACTER Variables to CHARACTER Values The FORTRAN-77 standard explicitly forbids initializing variables of any non-CHARACTER data type with CHARACTER values. Almost all FORTRAN-66 compilers do allow such initializations (they had to since there was no explicit CHARACTER data type in FORTRAN-66). SVS FORTRAN-77 therefore allows such initialization, provided the $CHAREQU option has been selected. For a description of the $CHAREQU option, see Chapter 13 "FORTRAN Compile Time Options". When the $CHAREQU compiler option is selected, non-CH~RACTER variables may be initialized with CHARACTER constants. Each character constant in the 'clist' initializes precisely one variable in the enlist'. If the length of the CHARACTER constant is longer than the number of bytes which the target variable occupies, the CHARACTER constant is truncated on the right to the same size as the target variable. If the CHARACTER constant is shorter in length than the number of b¥tes which the tar~et variable occupies, the CHARACTER constant is padded on the right with trailing spaces. In all cases, one ASCII character is stored in each byte of the target variable. Thus a variable of type REAL*4 would receive exactly four bytes, and a variable of type LOGICAL*l would receive exactly one byte. FORTRAN Reference Manual Page 53 Data Initialization Chapter 7 Example of Initializing ~-CHARACTER Variables • Select the option $CHAREQU • Declare some variables LOGICAL· 1 ARG DOUBLE PRECISION • • LARJ Initialize the variables DATA ARG, LARJ /'SING', 'SONG'/ In the example above, the variable ARG would receive the single character value'S' (because of truncation), while the variable LARJ would receive the value 'SONG '(because of space padding) • 7.3 Implied DO in DATA Statements As an added convenience, the DATA statement can incorporate a form of DO loop for initializing arrays (for example) in a regular and concise way_ This is known as an "implied-DO loop" and has the same form as a DO statement (see the chapter on "Control Statements"). The control variables of an implied-DO loop are declared implicitly and only for the duration of the DO loop. The following example should clarify the use of implied-DO loop initialization. In this case, the form of an implied-DO list in the DATA statement is: (dlist, i 'dlist' , i' = first, last [, inc]) is a list of array element names lists. and is the name of an integer variable, the implied-DO implied- DO-variable~ 'first', 'last' and 'inc' are each integer constant expressions. The expressions can contain implied-DO-variables of other implied-DO lists whose range includes this implied-DO list. The range of an implied-DO list is the list 'dlist'. An iteration count and the values of the implied-DO-variable are established from 'first', 'last' and 'inc' just as for a DO loop, but the iteration count must be positive. Page 54 FORTRAN Reference Manual Data Initialization Chapter 7 When an implied-DO list appears in a DATA statement, the items in 'dlist' are specified once for each iteration of the impliedDO list with the appropriate substitution of values for any occurrence of the implied-DO-variable tit. The implied-DO-variable can have the same name as a variable in the subprogram unit containing the DATA statement - there is no conflict of such names. Examples of Implied DO Loop Initialization C C Declare some large arrays. INTEGER PRIMES (1000) INTEGER UPRTRI(20, 20) REAL MATR~X(25, 80) C C C C Now initialize with DATA statements containing an implied-DO loop. = 1, DATA (PRIMES(I), I DATA «MATRIX(J, K), J C 1000) /1000*1/ = 1,80), K = 1, 25) /2000*1.0/ C C C The last DATA statement initializes the upper triangle of the array called~UPRTRI. C DATA «UPRTRI(I, J), J=l, 21-1),1= 1, 20) /210 * 0/ FORTRAN Reference Manual Page 55 Data Initialization Page 56 Chapter 1 FORTRAN Reference Manual Assignment Statements Chapter 8 Chapter 8 - Assignaent Stateaents An assignment statement computes a value which is then assigned to a program object. Because FORTRAN does not require that variables be declared ahead of time, it is possible that assignment actually causes that object to become allocated. There are four distinct types of assignment statements: • • • • 8.1 Arithmetic, Logical, Statement Label assignment (the ASSIGN) statement, Character assignment. Arithmetic Assignment Arithmetic assignment evaluates aR arithmetic assigns the result to a variable. The form is: variable expression, and expression 'variable' is a variable or an array element name, of type INTEGER, INTEGER*l, INTEGER*2, INTEGER*4 REAL, REAL*4, REAL*8, DOUBLE PRECISION or COMPLEX. 'expression' is an expression compatible types. with one of those If the type of 'variable' and the type of 'expression' are not compatible, the value of 'expression' is automatically converted to the type of 'variable' according to the following table. FORTRAN Reference Manual Page 57 Chapter 8 Assignment Statements I I I+------------------+-------------------+ +------------------+------~------------+ Type of variable or array element I Integer Value Assigned I INT(expression) I +------------------+-------------------+ I Real I REAL (expression) I +------------------+-------------------+ I Double Precision I DBLE(expression) I +------------------+-------------------+ I Complex I CMPLX(expression) I +------------------+-------------------+ Table 8-1 Type Conversion for Arithmetic Assignment Statements The functions in the "Value Assigned" column in the above table are generic intrinsic functions described in the table of intrinsic functions in the appendices. If an integer expression is of type INTEGER·l, INTEGER*2 or INTEGER*4, the result is automatically converted to the correct type. In general, an operand is "promoted" to the larger size when evaluating expressions. Operands of type INTEGER*l are always promoted to INTEGER*2. In the assignment statement, converting a longer INTEGER value to a shorter one is done by truncation. The FORTRAN-77 compiler does not issue any warning about it, and the running program issues no error m~·ssages because of truncation. Examples of Arithmetic Assignment INTEGER whole REAL party DOUBLE PRECISION COMPLEX house * • 8.2 DATA huge whole /10/, party /5.5/ whole = 50 * party party = 3.1415926388 * 5.7 huge = 547.987654e243 house = (1.0, -4.0) Logical Assignment Logical assignment assigns the value of an expression to a logical variable. The value of the expression must therefore evaluate to either of the values .TRUE. or .FALSE. The form of a logical assignment statement is: Page 58 FORTRAN Reference Manual Assignment .Statements Chapter 8 logical variable - logical expression If a logical variable is one of the types LOGICAL*l, LOGICAL*2 and LOGICAL*4, a logical expression is automatically converted to the correct type. Examples of Logical Assignment Statements LOGICAL TELLME, NONO TELLME - .TRUE. NONO 8.3 II: .FALSE. Statement Label Assignment Statement label assignment is used to assign the value of a format labey--Q[ a statement label to an integer variable. The form of statement label assignment is: ASSIGN statement-label TO integer-variable 'statement-label' is a format label or a statement label. 'integer-variable' is an integer variable. The integer ·variable must not be of type INTEGER*l or INTEGER*2. Executing an ASSIGN statement sets the integer variable to the value of the label. The label can be either a format label or a statement label. The label must appear in the same program unit unit as the ASSIGN statement. When used in an assigned GO TO statement, a variable must currently have the value of a statement label. When used as a format specifier in an input-output statement, a variable must have the value of a format statement label. The ASSIGN statement is the only way to assign the value of a label to a variable. Examples of Statement Label Assignment INTEGER SLAB, FORLAB ASSIGN 666 TO SLAB ASSIGN 905 TO FORLAB FORTRAN Reference Manual Page 59 Chapter 8 Assignment Statements 8.4 Character Assignment Character assignment evaluates a character expression and assigns the result to a character variable, character arrayThe form of a character element or a character substring. assignment statement is: character-variable - character-expression None of the character positions being defined in the left-hand side of the assignment may appear on the right-hand side of the assignment. If they do, the results are undefined. The left-hand side and the right-hand side of the assignment may be of different lengths. If the left-hand side is longer, the effect is to extend the right-hand side value to the right with spaces until it is the same length as the left-hand side. If the left-hand side is shorter, the effect is to take a substring starting at position 1 of the right-hand side, short enough to assign to the left-hand side. Only as much of the right-hand side need be defined as is necessary to define the left-hand side. For example, consider the following program fragment: CHARACTER fred*4, bill*8 fred = bill The assignment of 'bill' to 'fred' above requires that the substrin? 'bi1l(l:4)' be defined, since that is enough to define 'fred. It is not required that the rest of 'bill', 'bil1(5:8)', be defined. If the left-hand side of the assignment is a substring reference, the right-hand side is assigned only to the substring. The definition status of the character positions not defined on the left-hand side does not change. Page 60 FORTRAN Reference Manual Chapter 9 Control Statements Chapter 9 - Control Statements Control statements are used to direct the sequence of execution of a FORTRAN program. Control statements include constructs to execute statements selectively depending on the outcome of a logical expression (the block IF and logical IF statements), perform blocks of statements repetitively (the DO statement), to select one of a number of statements to execute depending on the value of an integer expression (the computed GO TO statement, and to terminate or suspend program execution (the STOP and PAUSE statements). This chapter covers the control statements of FORTRAN, in this order: Block IF THEN ELSE a "structured coding" construct which was introduced to FORTRAN with FORTRAN-77, newly Logical IF which executes or does not execute a subordinate statement depending on the truth or falsity of a logical expression, Arithmetic IF which executes a three-way branch depending the value of an arithmetic expression, DO which is FORTRAN's principal means of trol, CONTINUE which acts as a "null" statement, STOP to stop PAUSE to suspend program execution, progra~ loop on con- execution, Unconditional GO TO which unconditionally transfers another part of the program unit, control to Computed GO TO which selects a statement label to execute, depending on the value of an expression, Assigned GO TO which uses the value of an integer variable as statement label. FORTRAN Reference Manual a Page 61 Control Statements 9.1 Chapter 9 Block IF THEN ELSE Statement The block IF THEN ELSE statement group (described in the subsections below) represent "structured coding" constructs that control program execution flow without the need for indiscriminate jumping around via GO TO statements. As an overview of the subsections to follow, the three code skeletons below illustrate the basic ideas of the IF THEN ELSE statement groups. Skeleton 1 - a simple block IF which skips a ments if the expression is false: group of state- IF (I .LT. 10) THEN some statements that are executed ••••• only if I < 10 ENDIF Skeleton 2 - block IF with a series of ELSEIF statements. IF (J .GT. 1000) THEN ••••• some statements executed only ••••• if J > 1000 ELSE IF (J .GT. 100) THEN ••••• some statements executed only ••••• if J > 100 and <= 1000 ELSEIF (J .GT. 10) THEN ••••• some statements executed only ••••• if J > 10 and <= 100 ELSE ••••• some statements executed only if ••••• none of the above condit10ns were true ENDIF Skeleton 3 - shows that the constructs can be nested and that an ELSE statement can follow an IF block without intervening ELSEIF statements. The indentation is here to enhance readability - FORTRAN does not require it. IF (I .LT. 100) THEN some statements executed only •• if 1 < 100 IF (J .LT. 10) THEN •. some statements executed only •• if I < 100 and J < 10 ENDIF •• some more statements executed only if •• I < 100 ELSEIF (I .LT. 1000) THEN some statements executed only •• if 1 => 100 and I < 1000 IF (J .LT. 10) THEN •• some statements executed only Page 62 FORTRAN Reference Manual Control Statements Chapter 9 •• if I => 100 and I < 10000 and J < 10 ENDIF •• some more statements executed only if •• I -> 100 and I < 1000 ENDIF To provide a detailed understanding of the block IF and its associated statements, the concept of the IF-level is introduced. For any statement, its IF-level is: nl - n2 where 'nl' is the number of block IF statements (including the current statement) from the beginning of the current program unit and 'n2' is the number of ENDIF statements (not including the current statement) from the beginning of the current program unit. The IF-level of every statement must be greater than or equal to zero, and the IF-level of every block (IF, ELSEIF, ELSE and ENDIF) must be greater than zero. The IF-level of every END statement must be zero. The IF-level is used to define the nesting rules for the block IF and its associated statements and to define the extent of IF blocks, ELSEIF blocks, and ELSE blocks. 9.1.1 Block IF Statement The general form of the Block IF statement is: IF (logical expression) THEN Execution of the block IF statement involves evaluating the 'logical expression'. If the value is true and there is at least one statement in the IF block, the next statement executed is the first statement of the IF block. After the last statement in the IF block is executed, the next statement to be executed is the next ENDIF statement at the same IF-level as this IF statement. If the value is true and there are no executable statements in the IF block, the next statement to be executed is the next ENDIF statement at the same IF-level as this IF statement. If the value of the 'logical expression' is false, the next statement to be executed is the next ELSEIF, ELSE or ENDIF statement at the same IF-level as this IF statement. Note that transfer of control into an IF block from outside the IF block is not allowed. The bloqk IF statement, in fact, looks no different from the logical IF statement described later; however, the presence of the THEN keyword as the next statement indicates that a structured block IF statement group follows. FORTRAN Reference Manual Page 63 Control Statements 9.1.2 Chapter 9 ELSEIF Statement The form of the ELSEIF statement is: ELSEIF (logical expression) THEN The ELSE IF block associated with an ELSEIF statement consists of the (possibly zero) executable statements up to, but not including, the next ELSEIF, ELSE or ENDIF statement that has the same IF-level as this ELSE IF statement. Execution of an ELSEIF statement starts by evaluating the 'logical expression'. If the value is true and there is at least one statement in the ELSEIF block, the next statement executed is the first statement of the ELSEIF block. After the last statement in the ELSEIF block is executed, the next statement to be executed is the next ENDIF statement at the same IF-level as this ELSE IF statement. If the value of 'logical expression' is true and there are no executable statements in the ELSEIF block, the next statement to be executed is the next ENDIF statement at the same IF-level as this ELSEIF statement. If the 'logical expression' evaluates to false, the next statement to be executed is the next ELSEIF, ELSE or ENDIF statement that has the same IF-level as this ELSE IF statement. Note that transfer of control into an ELSEIF block from outside of that ELSEIF block is not allowed. 9.1.3 ELSE Statement The form of an ELSE statement is: ELSE The ELSE block associated with an ELSE statement consists of the (possibly zero) statements that follow the ELSE statement, up to, but not including, the next ENDIF statement that has the same IF-level as this ELSE statement. The "matching" ENDIF statement must appear before any intervening ELSE or ELSEIF statements at the same IF-level. In other words, there may only be one ELSE statement in a block IF statement. There is no effect in executing an ELSE statement. Note that transfer of control into an ELSE block that ELSE block is not allowed. Page 64 from outside FORTRAN Reference Manual Control Statements Chapter 9 9.1.4 ENDIF Statement The ENDIF statement marks the end of a form of the ENDIF statement is: block IF group. The ENDIF There is no effect in executing an ENDIF statement. There must be a -matching- ENDIF statement for every block IF statement in a program unit in order to specify which statements are in a particular block IF statement. 9.2 Logical IF Statement The logical IF statement evaluates an expression for logical TRUE or FALSE, then either executes or does not execute a following statement based on the truth or falsity, respectively, of the expression. The form of the logical IF statement is: IF (logical expression) statement where 'logical expression' is a logical expression, and 'statement' is any executable statement except a DO statement, Block IF, ELSEIF, ELSE, ENDIF statement, an END statement, or another logical IF statement. The 'logical expression' is evaluated, and if the value of the expression is true, the 'statement' is executed. If the 'logical expression' evaluates to false, the 'statement' is not executed and the execution sequence proceeds as if a CONTINUE statement had been encountered. Note that functions in the objects in the 'statement'. 'logical expression' can affect Example of Logical IF Statement IF (Token (1) 9.3 .NE. 32) RETURN Arithmetic IF Statement The arithmetic IF statement performs a GO TO to one of three statement labels depending on the value of an expression being negative, zero, or positive. The form of the arithmetic IF statement is: IF (expression) sl, s2, s3 FORTRAN Reference Manual Page 65 Chapter 9 Control statements The 'expression' in the description must be an INTEGER, INTEGER*l, INTEGER*2, INTEGER*4, REAL, REAL*4, REAL*S or DOUBLE PRECISION expression. 'sl', 's2' and 's3' are the statement labels of executable statements that appear in the same program unit as does the arithmetic IF statement itself. The same statement label can appear more than once among the three labels. The effect of the arithmetic IF statement is to 'expression' and select a label based upon the value. evaluate The statement labeled by 'sl' is executed if the value expression is less than ~. of the The statement labeled by 's2' is executed if the value expression is ~. of the The statement labeled by 's3' is executed if the value expression is greater than ~. of the The next statement executed is the statement labeled by the selected label. None of the labels may appear within the range of a DO loop or inside an IF, ELSEIF or ELSE block, unless the arithmetic IF statement itself is also in the same range or block. Example of the Arithmetic IF Statement IF (I - 100) 20, 30, 40 C 20 PRINT * , , I is less than 100' STOP C C 9.4 30 PRINT *, , I is exactly 100' STOP 40 PRINT *, , I is more than 100' STOP DO Statement - Loop Control A DO statement block is used for "loop control" purposes such as applying some operation to each element of an aggregate. The form of a DO statement is: DO s [,] i-e1, e2 [, , s' Page 66 e3] is the statement label of an executable statement. The label must follow this DO statement FORTRAN Reference Manual Chapter 9 Control Statements and be contained in the same program unit. , i' is an integer, real or double precision variable, called the DO-variable. 'el', 'e2' and 'e3' are each an integer, expression. real or double precision The statement labeled by's' is called the "terminal statement" of the DO statement. The terminal statement must not be an unconditional GO TO, assigned GO TO, arithmetic IF, block IF, ELSEIF, ELSE, ENDIF, RETURN, STOP, END or another DO statement. If the terminal statement is a·logical IF, it may contain any executable statement except those not permitted inside a logical IF statement. A DO statement is said to have 'a "range", beginning with the statement which follows the DO statement and ending with (and including) the terminal statement. If a DO statement appears in the range of another DO loop, its range must be entirely contained within the range of the enclosing DO loop. If a DO state~ent appears within an IF block, ELSEIF block or ELSE block, the range of the associated DO loop must be entirely contained in the particular block. If ,a block lF statement appears within the range of a DO loop, its associated ENDIF statement must also appear within the range of the DO loop. More than one DO loop can have the same terminal statement. The DO control variable, 'it, must not be set by any statement within the range of the DO loop associated with that control variable. Transfer of control into the range of a DO the range of a DO loop is not allowed. 9.4.1 loop from outside DO Loop Initialization Sequence Execution of a DO statement causes the following events to happen in order: the expressions 'el', 'e2' and 'e3' are evaluated, with conversion to the type of the DO variable if necessary, according to the rules specified for type conversion in the chapter on "Assignment Statements". If le3' is omitted, a default value of 1 is used. If 'e3' is present, it must not evaluate to zero, the DO variable 'it is set to the value of 'ell, FORTRAN Reference Manual Page 67 Control Statements Chapter 9 The iteration count for the DO loop is computed as: MAX(INT«e2 - el + el) / ell, 0) which may be zero, The iteration count is tested: if it exceeds zero, the statements in the range of the DO' loop are executed. DO' Loop Incrementation Processing 9.4.2 After the terminal statement of the DO' loop following events occur in order: is executed, the The value of the DO' control variable 'i! is incremented by the value of 'e3' which was computed when the DO' statement was executed, The iteration count is decremented by one (1), The iteration count is tested; if it exceeds zero, the statements in the range of the DO loop are executed again. The value of the DO control variable is well-defined, whether the DO' loop is exited as a result of the iteration count being zero, or as a result of an explicit transfer of control out of the DO' loop. • Example of the final value of a DO' control variable: This program fragment prints the number 1 thru lIon the console C C DO' 200 9.4.3 200 I = 1, 10 WRITE(*, '(IS)') I WRI TE (*, '( I 5) ') I Events Which Terminate a DO' Loop A DO' loop is exited under the following conditions: when its' iteration count is zero, as described above under "DO' Loop Execution Sequence", a RETURN statement is executed within loop, the range of the DO' control is transferred to a statement in the same program unit but outside the range of the DO' loop, Page 68 FORTRAN Reference Manual Control Statements Chapter 9 a subroutine called from within the range of the DO loop returns via an alternate return specifier to a statement which is outside the range of the DO loop, the program terminates for any reason. 9.5 CONTINUE Statement - Null Statement The CONTINUE statement is a "null" or "no operation" statement. It can appear just as any other statement in a program. CONTINUE has no effect on program execution. CONTINUE is almost always used as the final statement in a DO block, when the DO block would otherwise end in a statement that is disallowed in that context. The form of a CONTINUE statement is: CONTINUE 9.6 STOP Statement - Stop Program Execution The form of a STOP statement is: STOP [n] where Inl is either a character constant or a string of not more than five digits. The effect of executing a STOP statement is to cause the program to terminate. If the argument Inl is present on the STOP statement, it is displayed on the console upon termination. 9.7 PAUSE Statement - Suspend Program Execution The form of a PAUSE statement is: PAUSE [n] where Inl is either a character constant or a string of not more than five digits. The effect of executing a PAUSE statement is to cause the program to be suspended until there is an indication from the console that the program should proceed~ If the argument Inl ,is present on the PAUSE statement, it is displayed on the console as part of a prompt, requesting input from the console. If the indication is received from the console, program execution resumes as if a CONTINUE statement had been executed. 9.8 Unconditional GO TO Statement The ~nconditional GO TO causes an unconditional transfer of control to a specific labeled statement. The form of the unconditional GO TO statement is: FORTRAN Reference Manual Page 69 Chapter 9 Control Statements GO TO statement label The 'statement label' which is the target of the GO TO statement must be defined within the same program unit as the GO TO statement. The 'label' must be the statement 1abel of an executable statement. Transfer of control into a DO, IF, ELSEIF or ELSE block from outside such a block is not allowed. 9.9 Computed GO TO Statement A computed GO TO statement acts as a means of transferring control to one out of a set of labeled statements, depending on the value of an expression. The form of the computed GO TO statement is: GO TO ( s [, s ] ...) [, ] i where 'i' is an integer expression and each's' is a statement label of an executable statement in the same program unit as the computed GO TO statement. The same statement label may appear more than once in the list of statement labels. The effect of the computed GO TO statement is to evaluate the integer expression indicated by 'if to a value, say n. Control is then transferred to the n'th statement label in -the list, counting from 1. If the value of n is less than 1, or if the value of n is greater than the number-of statement labels in the list, the computed GO TO statement has no effect, and program execution proceeds as if a CONTINUE statement had been executed. The same restrictions on transfer of control apply to the computed GO TO statement as those that apply to the unconditional GO TO statement. Example of Computed GO TO Statement WHERE = 3 GO TO (100, 200, 300, 400, 500), WHERE .•••• execution continues here when 5 < WHERE < 1 C 100 statements executed if WHERE .. I 200 statements executed if WHERE 300 statements executed if WHERE = 3 400 statements executed if WHERE = 4 500 statements executed if WHERE =- 5 C 2 C C C Page 70 FORTRAN Reference Manual Chapter 9 9.10 Control Statements Assigned GO TO Statement The assigned GO TO statement uses the value of an integer variable as a statement label which is to be the target of a GO TO statement. The effect is as if an unconditional GO TO had been made to that statement label. The form of the assigned GO TO is: GO TO i [[,] (s[, s] ••• )] where Ii' is the name of an integer variable and each's' is a statement label of an executable statement in the same program unit as the assigned GO TO statement. The same statement .label may appear more than once in the list of statement labels in an assigned GO TO statement. At the time the assigned GO TO is executed, the integer variable 'i' must be defined with the value of a statement label of an executable statement which appears in the same program unit as the assigned GO TO statement. That variable must have been defined with an ASSIGN statement. The integer variable 'i' must be of type INTEGER or INTEGER*4. It must not be of type INTEGER*l or INTEGER*2. If the optional, parenthesized list of statement-labels is present, the value of the integer variable Ii' must be that of one of the statement-labels in the list. The same restrictions apply to the assigned GO TO statement as those that apply to the unconditional GO TO statement. Example of Assigned GO TO Statement ASSIGN 645 TO SYSTEM GO TO SYSTEM, (360, 370, 635, 645, 1108) 645 statements starting here will be executed because 'SYSTEM' has the value 645. FORTRAN Reference Manual Page 71 Control Statements Page 72 Chapter 9 FORTRAN Reference Manual Input and Output Chapter 10 Chapter 10 - Input and Output This chapter and Chapter 11 describe the FORTRAN input-output system. This chapter covers the basic concepts of input and output in FORTRAN. Chapter 11 describes the FORMAT statement. Topics covered in this chapter and Chapter 11 are: an overview of the input-output system. Covers the basics of the FORTRAN file system. Defines the ideas of records, units and various forms of file access, a general coverage of the input-output system, input-output statements are covered, with the exception of the FORMAT statement, ~hich is covered in Chapter 11. 10.1 Overview of the Input-Output System This section introduces the basic terms and concepts of the FORTRAN input-output system. Most tasks related to input-output can be done without a full understanding of this section, so the reader can skip to the next section on first reading and use this section for subsequent reference purposes. 10.1.1 Records A record is the building block of the FORTRAN input-output system. A record is a sequence of characters or a sequence of values. There are three forms of records: • Formatted records, • Unformatted records, • Endfile records. A formatted record is a sequence of characters terminated by the character value corresponding to the "end-of-line" key on a terminal (character value 13, or 10, or both, depending on the particular operating system). Formatted records are interpreted consistently on input the same way that the underlying operating system and any text editor interprets characters. A formatted record therefore corresponds to the notion of a "line" from a FORTRAN Reference Manual Page 73 Input and Output Chapter 10 device. Formatted files are normally transportable between different language processors and other text-processing applications. An unformatted record is a sequence of values. The system does not alter or interpret such records in any way; neither is there any representation for an end-of-record as is the case with a formatted record. Unformatted files are generally not transportable between different language processors or computers because of differences in the external representations of data. An endfile record has no physical existence in a file, but the underlying input-output system supplies an indication of one, as if there had been some actual record after the last record in a file. 10.1.2 Files A FORTRAN file is a sequence of either Externar-or Internal. records. FORTRAN An external FORTRAN file is a file on a physical device or it is an actual peripheral device. files are peripheral An internal FORTRAN file is a character variable which is to serve as the source or destination of some input-output action. From here on, FORTRAN files and the files known to the underlying operating system and any text processors are simply called "files". The correct meaning is determined by the context. The OPEN statement provides the association between the two notions of files, and in most cases, there is no ambiguity after the file is opened - the two notions of a file being the same. 10.1.3 Properties of Files A file which is being operated upon by a FORTRAN program has a number of properties which are described in the paragraphs below. File properties which are discussed below encompass: • • • • Name of the file, Position of the file, Record format, Access method. 10.1.3.1 File Name A file can have a name. If the name is present, it is a character string identical to that by which it is known to the operating system. A file can have a name such as Page 74 FORTRAN Reference Manual Chapter 10 Input and Output '/source/fourier.text'. 10.1.3.2 File Position A file has the property of position which is usually established by the preceding input-output operation. There is the notion of the beginning-of-file, endfile, the current record, the preceding record, and the next record in the file. It is possible to be between records, in which case the next record is the successor to the previous record, and there is no current record. The position of the file after a sequential write is the endfile but not beyond the endfile record. Executing an ENDFILE statement positions the file beyond the endfile record. A READ statement executed at end-of-file (but not beyond the endfile record) positions the file beyond the endfile record. The user can trap reading of an endfile record via the END= option in a READ statement. 10.1.3.3 Formatted and Unformatted Files An external file is opened as either formatted or unformatted. Internal files are always formatted. Formatted files consist entirely of formatted records. Unformatted files consist entirely of unformatted records. Formatted files have the structural properties of being a sequence of lines with end-of-line indicators (usually carriage-return). 10.1.3.4 Sequential and Direct Access Files An external file is opened as either sequential access or direct access. Sequential files contain records in an order determined by the order in which they were written. Sequential files must not be read or written using the REC= option which specifies a position for direct-access input-output. The system attempts to extend sequential access files if a record is written beyond the old endfile, if there is enough room to do this on the external device. Direct-access files can be written in any order (random access). Records in a direct-access file are numbered sequentially with the first records having the number one (1). All records in a direct-access file have the same length, specified when the file is opened. Each record in the file is uniquely referenced by its record number, specified at the time the record is written. Records can be written out of order, with holes in the sequence if desired. For example, records 9, 5 and 11 could be written in that order without writing the intermediate records. Once written, a record cannot be deleted, but a record can be rewritten with a new value. It is an error to read a record that has not yet been written, but the system can only FORTRAN Reference Manual Page 75 Input and Output Chapter 10 detect this if the attempted read is to a record beyond the highest numbered record in the file. Direct-access files must reside on block-structured storage devices, such that a position in the file is meaningful. The system attempts to extend a direct-access file if a write is made to a position beyond the current highest numbered record in the file, but the success of this depends on the amount of space on the storage device. 10.1.4 Internal Files Internal files provide a means for using the formatting capabilities of the input-output system to convert values to and from their external character representations, within FORTRAN's internal storage structures. That means that reading from a character variable converts the character values into numeric, logical or character variables. Writing to a character variable converts values into their external character representation. 10.1.4.1 Special Properties of Internal Files An internal file is a character variable, character array element, character array or character substring. A record of an internal file is a character variable, character array element or character substring. If an internal file is a character variable, character array element or character substring, such a file has exactly one element, whose length is that of the character variable, character array element or character substring. If an internal file is a character array, each element of that array is a record of the file, with each record being the same length. If less than an entire record is written by a WRITE the remainder of the record is filled with spaces. statement, The position of an internal file is always at the beginning of file prior to executing any input-output statement. Only sequential, formatted input-output is allowed on an internal file. Only the READ and WRITE statements can reference an internal file. List-directed input-output is not allowed on an internal file. 10.1.5 Units A unit is a means of specifying a file. input-output statement is either of: A unit specified in an • External unit specifier, • Internal unit specifier. Page 76 FORTRAN Reference Manual Chapter 10 Input and Output An external unit specifie~ is either a positive integer expression or the character * which stands for the Standard Input and Standard Output files for the running program. In most cases, external unit specifiers are bound to physical devices (or files on those devices) by name when the OPEN statement is executed. Once this binding of a value to a system file name has occurred, FORTRAN input-output statements refer to the unit number as a means of referring to the external object. Once opened, the external unit specifier is uniquely associated with the external device or file until an explicit CLOSE statement is executed or until the program terminates. Unit specifier 0 (zero) is initially associated with the Standard Input and Standard Output files for reading and writing (respectively) and an explicit OPEN statement is not needed. The system interprets the character * as specifying unit O. Similarly, the unit specifier 1 (one) is associated with the Standard Error file if one exists in the system, or the Standard Output otherwise. No other unit specifiers are initially available (without explicit OPEN statements) and in particular, unit specifiers 5 and 6 have no special or initial properties as they had in certain earlier FORTRAN dialects. An internal unit identifier is the name of a character variable, character array, character array element or character substring.Internal unit specifiers may only be used in the READ, WRITE and PRINT statements - they are not allowed in any of the auxiliary input-output statements such as OPEN, CLOSE, INQUIRE and so on. 10.2 General Discussion of the Input Output System FORTRAN supplies a rich selection of possible file structures. At first there might seem to be a confusing array of choices. However, two sorts of files will probably suffice for most applications. The Standard Input and Standard Output files. These are referred to as unit 0 or by the character *. The Standard Input and Output files are sequential, formatted files. When reading from the Standard Input, the backspace and line-delete keys familiar to the user have their normal editing functions. The Standard Output file has the special property that it is possible to write partial lines to it (lines which are not terminated by a carriage-return) by using the "\" or "$" edit descriptors. These edit-descriptors are described in the next chapter. Writing to any other unit does not have this property, even if that unit is explicitly bound to the Standard Output file by an OPEN statement. Explicitly-opened These files are external, bound to FORTRAN Reference Manual sequential, formatted files. a system file by name in an OPEN Page 77 Chapter 10 Input and Output statement. These files can be processed by system editors and other text-processing utilities. 10.2.1 Pre-Connected Files The FORTRAN run-time system preconnects unit 0 to the Standard Input and Standard Output files, as mentioned above. On those operating systems which support a standard error file, the FORTRAN run-time system also preconnects unit 1 to that stream. On those systems which do not support a standard error file, the FORTRAN run-time system preconnects unit 1 to the same place as the Standard Output. 10.2.2 Examples of Common Input Output Operations Here is an example program reading and writing the sorts of files discussed in the paragraph above. The specific inputoutput statements are discussed in detail in the next section. C C C C C Copy a file containing three columns of integers, each column being 1 characters wide. The user supplies the name of the input file. The output file is called OUT.TEXT. The first and second columns are swapped. C PROGRAM SWITCH CHARACTER*23 FNAME INTEGER FIRST, SECOND, THIRD C C Prompt to the Standard Output by writing to * C WRITE(*, 900) 900 FORMAT ( , I npu t file name C C C _ '\) Read the file name from the Standard Input by reading READ(*, 910) 910 FORMAT (A) FNAME C C C Use unit 3 for input - any uni~ but 0 will do. OPEN(3, FILE=FNAME) C C C Page 78 Use unit 4 for output - any but 0 and 3 are ok. OPEN(4, FILE='OUToTEXT', STATUS='NEW') FORTRAN Reference Manual * Chapter 10 C C Input and Output Read and write until end-of-file. C 100 READ(3, 920, END=200) FIRST, SECOND, THIRD WRITE(4, 920) SECOND, FIRST, THIRD 920 FORMAT(3I7) GO TO 100 C 200 WRITE(., 910) 'Done Copying' END 10.2.3 Less Common File Operations The less common file structures are suitable for certain classes of applications. In general, the appli9ation areas are these: Direct-access files are suitable for random access applications such as maintaining a database. Unformatted files are more efficient in input-output overhead and in file space requirements. Unformatted access can be used if data is to be writtep and read by FORTRAN on the same processor. The combination of direct-access and unformatted files is ideal for a database management facility to be accessed exclusively through the FORTRAN system. If data is to be transferred without any system interpretation (especially if all 256 character combinations are needed), unformatted input output is necessary, since .TEXT files are limited to the printable character set. A good example of unformatted input-output usage is to control a device with a single-byte binary interface. In this situation, formatted input-output would interpret certain characters (such as carriage-return) and would change their meanings in certain ways. Internal files are not input-output in the conventional sense but they provide valuable character string operations and conversion via a standard mechanism. Formatted direct-access files require special care. FORTRAN formatted files try to comply with the operating system's rules for ASCII files. This allows standard system utilities such as editors to be used on these files. The FORTRAN input-output system is able to enforce these rules for sequential files, but cannot always enforce them for direct-access files. Direct-access files are not necessarily valid ASCII files and may not work properly with other system utilities, since any unwritten records leave "holes" which do not follow the operating system's rules for ASCII files. Direct-access files do, of course, follow FORTRAN Reference Manual Page 79 Input and Output Chapter 10 FORTRAN'S input-output rules. A file opened in FORTRAN is either "old" or "new". There is no notion of "open for reading" as distinct from "open for writing". Therefore ·old" (existing) files may be opened and written on, with the effect of changing an existing file. Similarly the same file may be alternately read from and written to, providing that no attempts are made to read beyond end-of-fi1e or to read unwritten records in direct-access files. A write to a sequential file effectively deletes any records which existed beyond the fresh record. Normally, when a device (such as a terminal) is opened as a file, it makes no difference whether it is "new" or "old". with disk files, opening "new" creates a new file. If that file is closed with the "keep" option, or the program terminates before a CLOSE is performed on that file, a permanent file is created with the name given when the file was opened. If a file is closed using the "delete" option, the newly created file is deleted. In either case, if a file existed previously with the same name, the prior version is deleted. Opening a disk file as "old" generates a run-time error if the file does not exist1 if it does exist, any writes to that file change its contents. 10.2.4 Limitati,ons of FORTRAN Input Output System This subsection discusses specific limitations input-output system imposes. 10.2.4.1 that FORTRAN's Direct Files must be on Blocked Devices The operating system underlying FORTRAN has two kinds ices, namely blocked and sequential. of dev- Sequential files can be considered a stream of characters with no explicit positioning; the only operations are reading and writing. The Standard Input and Standard Output are examples of sequential devices. Blocked devices, such as disks, have the additional capability to seek to a specific position. Blocked devices can be accessed either sequentially or randomly and therefore can support direct-access files. Since there is no notion of seeking to a position on an unblocked file, FORTRAN prohibits direct access to sequential devices. 10.2.4.2 No Character Compression in Direct Files Direct-access formatted files must not compression information. Page 80 contain any, character FORTRAN Reference Manual Chapter 10 10.2.4.3 Input and Output BACKSPACE Only Applies to Files on Blocked Devices BACKSPACE can only be performed on files associated with blocked devices, it cannot be applied to sequential devices. 10.2.4.4 Length Limitations-on Formatted Records Formatted records must not be greater than 512 characters length, including the terminating carriage-return character. 10.2.4.5 in BACKSPACE may not be used on Unformatted Sequential Files It is not possible to apply the BACKSPACE statement to an unformatted sequential file, because such a file contains no indications of its record boundaries. In principle it is possible to place end-of-record marks in such a file format, but this conflicts with the notion of an unformatted file as a "pure" sequence of values. Any structure imposed upon unformatted sequential files would interfere with their most common application, which is direct control of external instruments. 10.2.4.6 Side Effects of Functions Used in Input Output Statements During execution of any input-output statement, expression evaluation can reference functions. Any function so referenced must not execute any other input-output statement. 10.3 Elements of Input and Output Statements This section describes the elements that comprise input and output statements that FORTRAN supports. The next section covers the individual input-output statements in detail. FORTRAN input-output statements require certain arguments and parameters which specify sources and destinations of data transfer, as well as other aspects of the operation. 10.3.1 The Unit Specifier 'u' The unit seecifier indicates the unit to be used in output operatlons. The format of a unit specifier is: input- [UNIT=] u where 'u' is an external or internal unit identifier. FORTRAN Reference Manual Page 81 Input and Output Chapter 10 The unit identifier, input-output statement: • lUi, can take one of these refers to the Standard Input or filese forms in Standard an Output positive integer expression refers to an external file whose unit number is that of the expression. Unit 0 is the same as * - the Standard Input or Standard Output files. name the name of a character variable, character array, character array element or character substring. In all input-output operations, if the UNIT: keyword is omitted, the unit specifier, 'UI, must be the first item in the list of specifiers. 10.3.2 The Format Specifier If I The format specifier is used to designate format lists when performing formatted input-output. The form of the format specifier is: [FMT=] f where 'f' is the format identifier, and can forms in an input-output statement: take statement label refers to the FORMAT statement statement label. one labeled of these by that integer variable name refers to the FORMAT label assigned to that integer variable using the ASSIGN statement. character expression the current value of the character expression the format specifier. is asterisk character '*' the asterisk is formatting. used to specify list-directed If the FMT= keyword is omitted in a list of specifiers, the format specifier, 'fe, must be the second item in the list and the unit specifier, lUi, must be the first item in the list, with Page 82 FORTRAN Reference Manual Chapter 10 Input and Output the UNIT= keyword omitted. See Chapter 11 for a complete description of and the elements it may contain. 10.3.3 the format list The Record Number ern' The record number is used in direct-access input-output only. It specifies the number of the record to be read or written. The format of the record number specifier is: REC=rn where ern' is the record number. positive integer. 10.3.4 The record number must be a The End of File Exit Specifier The end-of-file exit specifier designates a statement label at which execution is to start when an end-of-file condition occurs while reading from a file. The format is: ENO=s where 's' is a statement label in the same program READ statement. 10.3.5 unit as the The Error Exit Specifier The error exit specifier designates a statement label at which execution is to start when any errors occur during execution of an input-output statement. The format of the error exit specifier is: ERR=s where IS' is a statement label in the same program input-output statement. 10.3.6 unit as the The Input Output Status specifier 'ios' The input-output status specifier specifies an integer variable into which an input-output status value is placed when the current input-output statement completes. The. format of the specifier is: IOSTAT=ios where 'ios' is the name of an integer variable or FORTRAN Reference Manual integer array Page 83 Input and Output Chapter 10 element. The integer variable specified by 'ios' must be an INTEGER (or INTEGER*4). When an input-output statement containing this specifier terminates, 'ios' becomes defined with the following values: zero (0) indicates that the input-output operation completed normally. There were no errors and endof-file was not encountered, negative value indicates that an end-of-file during a READ statement, positive value indicates that an error condition occurred during the input-output statement. 10.3.7 was encountered The Input-Output List 'iolist' The input-output list - 'iolist' - specifies the objects whose values are transferred by READ and WRITE statements. An 'iolist' can be empty. If an Violist' is present, it is a list of elements separated by commas. Items in the list consist of: • Input and output objects, • Implied DO lists. These two forms of 'iolist' are discussed in the two paragraphs below. 10.3.7.1 Input and Output Objects An input or output object can be specified in the 'iolist' of a READ, WRITE or PRINT statement and is one of these forms: Variable name, Array element name, Character substring name, Array name. This form is a means of specifying all the elements of the array, in the order in which they are stored internally, On output only, any other expression except a character expression which concatenates an assumed length character string. Example of Input and Output WRITE (0, 100) 'Results are: Page 84 widget, blivet(j, 4) FORTRAN Reference Manual Chapter 10 Input and Output 100 FORMAT (A, IS, FIO.S) 10.3.7.2 Implied DO Lists Implied-DO lists can be specified as items in the 'iolist' READ, WRITE and PRINT statements and are of the form: of (dlist , i - e l , e2 [, e3l) where the 'dlist' is an 'iolist' as defined previously •• In a READ statement, the DO variable, 'it, (or an associated object) must not appear as an input list item in the embedded 'dlist', but can be read in the same READ statement outside of the implied-DO list. The embedded 'dlist' is effectively repeated for each iteration of Ii' with appropriate substitution of values for the DO control variable 'it. Example of WRITE (0, ISO) ISO FORMAT (1017) !!! Implied DO List (jinx(i), i = 1, 100) In the example above, the variable Ii' iterates through 100 elements of the array 'jinx'. The format specified in the FORMAT statement causes the results to be placed 10 per line on the output. 10.4 The Specific Input and Output Statements The following input-output statements are supported in the FORTRAN system. The possible form of each statement is specified first, with an explanation of the meanings of the following forms. Certain items are specified as required if they must appear in the statement and are specified as optional if they need not appear in the statement. Optional items normally result in a default which is indicated if the item is omitted. 10.4.1 OPEN Statement The format of the OPEN statement is: OPEN(open list) where 'open list' is a list of specifiers as described below. The argument list, 'open list' must contain one unit specifier FORTRAN Reference Manual Page 85 Input and Output Chapter 10 and may contain one of each of the other specifiers listed. (UNIT=]U 'u' is the unit specifier. It must not be an internal unit specifier. If the UNIT= keyword is· omitted, the 'u' argument must be first in the argument list to OPEN. IOSTAT=ios 'ios' is an input-output status specifier as defined above in "Elements of Input and Output Statements". ERR=s is an error exit specifier as defined above "Elements of Input and Output Statements". FILE=fname The file name 'fname' is a character expression. If the 'fname' argument is omitted, OPEN opens a an anonymous file with a status of 'SCRATCH' (see below) • This file is automatically deleted when CLOSE'd or upon program termination. STATUS=sta 'stat is the status of the file when opened. 'stat is a character expression whose ~alue must be one of 'OLD', 'NEW', 'SCRATCH' or 'UNKNOWN'. 'OLD' is the default for reading or writing existing files. 'NEW' may be used for writing new files. If the 'OLD' or 'NEW' keywords are used, the FILE= argument must be supplied. If 'SCRATCH' is specified, the file is deleted when a CLOSE is performed on that file. If 'UNKNOWN' is specified, it is treated the same as if 'OLD' had been specified. ACCESS=acc specifies the access mode for this file. 'acc' is a character expression whose value must be either 'SEQUENTIAL' or 'DIRECT'. 'SEQUENTIAL' is the default. FORM=fm specifies whether the file is formatted or unformatted. 'fm' is a character expression whose value must be either 'FORMATTED' or 'UNFORMATTED'. 'FORMATTED' is the default. RECL=rl The record length 'rl' is an integer expression. This argument to OPEN is for DIRECT-access files only and is required for that file type. BLANK=blnk 'blnk' controls the default treatment 6f blanks (spaces) in formatted reads, which can be altered, in a particular formatted READ, by a 8N or 8Z edit-descriptor in a format specification. 'blnk' is a character expression whose value must be either 'NULL' or 'ZERO', The default is 'NULL'. If 'NULL' is specified, all spaces are Page 86 in FORTRAN Reference Manual Chapter 10 Input and Output ignored in numeric input fields. If 'ZERO' is specified, all spaces other than leading spaces are treated as zeros. BUFFERED='buffered' The BUFFERED option selects buffered or unbuffered input or output on a unit in the system. If the option is 'BUFFERED', buffered input output is selected. If the option is 'UNBUFFERED', unbuffered input output is selected. Note that the operating system might override the option. Some operating systems show a substantial improvement in throughput if the 'BUFFERED' option is selected. All files are opened with the 'BUFFERED' option by default, except for the * unit and unit I (the standard error). The OPEN statement binds a unit number with an external device, or file on an external device, by specifying its file na~e. If the file is to be a direct access file, the REeL=rl option specifies the length of records in that file. If the unit specified in an OPEN statement is already open, it is closed before being bound to a file. 10.4.2 CLOSE Statement The format of the CLOSE statement is: CLOSE(close list) where 'close list' is a list of specifiers. 'close list' must contain an external unit specifier and at most one of any of the other specifiers, which are as follows: [UNIT=]u· 'u' is the unit number of an external unit. If the UNIT= keyword is omitted, the unit specifier, lUI, must be the first specifier in the list. IOSTAT=ios 'ios' is an input-output status specifier as defined above in "Elements of Input and Output Statements". ERR=s 's' is an error exit specifier as defined above in "Elements of Input and Output Statements". STATUS=sta 'stat is an optional argument which dictates the disposition of the file after it is CLOSE'd. 'stat is a character expression whose value must be either 'KEEP' or 'DELETE'. FORTRAN Reference Manual Page 87 Input and Output Chapter 10 CLOSE disconnects the specified unit and prevents input-output from being directed to that unit (unless the same unit number is re-opened, possibly bound to a different file or device). Files are discarded if STATUS='DELETE' is specified. Normal te~mina tion of a FORTRAN program automatically closes all open files as if a CLOSE with STATUSa'KEEP' had been specified. STATUS-'KEEP' should not be specified for a file which was opened as 'SCRATCH'. 10.4.3 READ, WRITE and PRINT Statements The READ statement transfers data into storage. The WRITE and PRINT statements transfer data from storage. All three statements have similar forms, as defined here: READ (control list) [iolist] READ f WRITE (control list) [iolist] PRINT f [, iolist] [, iolist] where 'f' and 'iolist' are a format identifier and an inputoutput list as previously described in "Elements of Input and Output Statements". Note that the PRINT statement has no connection with "printing" on the system printer device (even if such a device exists). The 'control list' is a list whose elements may be any following: of the [UNIT=] u is a unit specifier. If the optional UNIT= keyword is omitted from the specifier, the unit specifier, 'u', must be the first item in the list. [FMT=] f is a format specifier. If the optional FMT= keyword is omitted from this specifier, the format specifier, Iff, must be the second item in the list and the first item must then be the unit specifier, 'u', without the UNIT= keyword. REC=rn a record nu~ber specifier. If this specifier included 1n the list, the statement is a direct-access data transfer statement, otherwise the statement is a sequential access data transfer. ~s 1S IOSTAT=ios Page 88 'ios' is an input-output status specifier as defined above in "Elements of Input and Output Statements". FORTRAN Reference Manual Chapter 10 Input and Output 's' is an error exit specifier as defined above in "Elements of Input and Output Statements". is an end-of-file exit specifier as defined above in "Elements of Input and Output Statements·. This specifier is only applicable to the READ statement. If the 'control list' contains a format specifier, the statement is a formatted input-output statement, otherwise it is an unformatted input-output statement. If the format identifier is an asterisk character, '*', the statement is a list-directed input-output statement. In this case, the record specifier must not appear in the 'control list'. List-directed input-output must not be done on an internal file. If the unit specifier designates an internal file, the 'control list' must not contain a record specifier. The end-of-file specifier must not appear in the 'control list' for a WRITE or PRINT statement. The 'control list' must not contain both a record specifier and an end-of-file specifier. 10.4.4 File Positioning Statements FORTRAN supplies three statements which position citly: files BACKSPACE to backspace a file by one record. ENDFILE to write an endfile record on a file. REWIND to position or re-position a file record. Each of the forms: file positioning statements has at two its expli- first different BACKSPACE u BACKSPACE (alist) ENDFILE ENDFILE (alist) REWIND REWIND (alist) u u In each case, the 'u' is a unit number. The parenthesized list of specifiers of the form: FORTRAN Reference Manual 'alist' is a Page 89 Input and Output Chapter 10 [UNIT s 1u 'u' is a unit specifier for the unit. This argument is required. If the UNIT= keyword is omitted, the 'u' argument must be first in the list. IOSTAT=ios 'ios' is an integer variable which is assigned the status of the specific input-output statement. 'ios' is defined previously in "Elements of Input and Output Statements". ERR=s IS' is a statement label -to which control is passed if there are any errors in the inputoutput statement. The statement label '9' must appear in the program unit that contains the input-output statement. 'Sf is defined previously in "Elements of Input and Output Statements". 10.4.4.1 BACKSPACE Statement - Backspace a File BACKSPACE positions the file connected to the specified unit, before the preceding record. If there is no preceding record, the file position is not changed. If the preceding record is the endfil~ record, the file is positioned before the endfile record. A non-connected unit may be BACKSPACE'd without any error. In other words a BACKSPACE command issued against a non-connected unit has no effect. BACKSPACE can only be issued on units which are formatted. BACKSPACE must not be applied to a unformatted file. 10.4.4.2 sequentialsequential- ENDFILE Statement - Write an Endfile Record ENDFILE "writes" an endfile record as the next record on the file connected to the specified unit 'u'. The file is then positioned after the endfile record, so that further sequential data transfers are prohibited until either a BACKSPACE or a REWIND statement is executed. 10.4.4.3 REWIND Statement - Rewind a File The REWIND statement positions the file associated with unit 'u' to its initial point. The unit must be sequential. the A non-connected unit may be rewound without any error. In other words a REWIND command issued against a non-connected unit has no effect. Page 90 FORTRAN Reference Manual Input and Output Chapter 10 10.4.5 INQUIRE Statement - Obtain File Properties The INQUIRE statement is used to obtain information about the properties of a particular named file or about the connection to a particular unit. There are two forms of INQUIRE, namely, inquire by file and inquire by unit. The INQUIRE statement can be executed before, while or after a file is connected to a unit. Any values assigned as a result of INQUIRE are values which are current at the tim. the INQUIRE is executed. The two forms of the INQUIRE atatement are: INQUIRE (iflist) 2! INQUIRE (iulist) where 'iflist', used for the inquire by file form, is a list of specifiers containing exactly one file specifier and 'iulist', used for the inquire by unit form, is a list of .pecifiers containing exactly one unit specifier. Both for •• may then contain other specifiers as described below. The format of the file specifier is: FILE-fin where 'fin' is a character expression which, when trailing spaces are removed, is the name of the file which is the subject of the inquiry. The named file does not need to exist or to be connected to a unit. The form of the unit specifier is as· described previously in "Elements of Input Output Statements". Tne unit specified does not have to exist, nor be connected to a file. If the unit is connected to a file, the inquiry is being made about the connection and the,jile connected to it. The remainder of the list in the INQUIRE statement is the inquiry specifiers. This is a list of one or more inquiry specifiers as described below. There may be only one of each inquiry specifier. Furthermore, each variable name may only appear once in the list of specifiers, in other words, the same variable name must not be given to more than one specifier. The inquiry specifiers are summarized more detail below. FORTRAN Reference Manual here and described in Page 91 Input and Output Chapter 10 +-------------------+ IOSTAT = ios ERR =- s EXIST = ex OPENED = od NUMBER =- num NAMED =- nmd NAME = fn ACCESS =- acc SEQUENTIAL =- seq DIRECT =- dir FORM =- fm FORMATTED = fmt UNFORMATTED = unf RECL =- rcl NEXTREC = nr BLANK = blnk +-------------------+ In every case where an integer variable is specified, it must be an INTEGER*4 (which is the same as INTEGER). In all cases where a logical variable is specified, it must be a LOGICAL*4 (which is the same as LOGICAL). The specifiers given here are as defined previously in "Elements of Input and Output Statements". The meaning of each of the inquiry specifiers is as follows: IOSTAT=ios is an input-output status specifier. The variable 'ios' is set to zero (0) by the INQUIRE statement. ERR=s IS' is a statement label to which control is passed if an error occurs. The INQUIRE statement never causes any error conditions. EXIST=ex 'ex' is a LOGICAL*4 variable. If a file with the specified name exists (in the FORTRAN milieu) 'ex' is set to .TRUE., else 'ex' is set to .FALSE. For an inquire by unit, 'ex' is set to true if and only if the unit actually exists. 'ex' always gets defined by the INQUIRE statement. OPENED=od cod' is a LOGICAL*4 variable. If the specified file is opened (connected to a unit), lode is set to .TRUE., else 'ode 1S set to .FALSE. 'ode always gets defined by the INQUIRE statement. NUMBER=num 'nurn' is an INTEGER*4 variable. 'num' is set to the the external unit number for the unit currently connected to the file. If the file is not connected to a unit, 'num' is undefined. Page 92 FORTRAN Reference Manual Input and Output Chapter 10 NAMEO=nmd If the file has a name, the LOGICAL*4 variable 'nmd' is set to .TRUE., else 'nmd' is set to .FALSE. NAME=fn 'fn' is a character variable that is set to the name of the file if the file has a name. If the file does not have a name, 'nmd' is undefined. ACCESS=acc 'acc' is a character variable that is assigned the string 'SEQUENTIAL' if the file is connected for sequential access, and is assigned the value 'DIRECT' if the file is connected for direct access. If the file is not connected to a unit, the value of 'acc' is undefined. SEQUENTIAL=seq 'seq' is a character variable which is assigned the value 'YES' if this file can be connected for sequential access. 'seq' receives the value 'NO' if the file cannot be connected for sequential access. If FORTRAN cannot determine what access methods are allowed for the file, 'seq' receives the value 'UNKNOWN'. DIRECT=dir 'dirt is a character variable which is assigned the value 'YES' if this file can be connected for direct access. 'dirt receives the value 'NO' if the file cannot be connected for direct access. If FORTRAN cannot determine what access methods are allowed for the file, 'dirt receives the value 'UNKNOWN'. FORM=fm 'fm' is a character variable which is assigned the value 'FORMATTEO' if the file is connected for formatted input-output, and is assigned the value 'UNFORMATTED' if the file is connected for unformatted input-output. If the file is not connected, 'fm' is undefined. FORMATTEO=fmt 'fmt' is a character variable which is assigned the value 'YES' if this file can be connected for formatted input-output. 'fmt' receives the value 'NO' if the file cannot be connected for formatted input-output. If FORTRAN cannot determine if the file can be connected for formatted inputoutput, 'fmt' is assigned the value 'UNKNOWN'. UNFORMATTED=unf 'fmt' is a character variable which is assigned the value 'YES' if this file can be connected for unformatted input-output. 'unf' receives the value 'NO' if the file cannot be connected for unformatted input-output. If FORTRAN cannot determine if the file can be connected for unformatted input-output, 'unf' is assigned the value FORTRAN Reference Manual Page 93 Chapter 10 Input and Output 'UNKNOWN' • RECL-rcl 'rcl' is an INTEGER*4 variable which is assigned the record length of the file connected for direct access. If the connection is not for direct-access or the the file is not connected at all, 'rcl' is undefined. NEXTREC=nr 'nr' is an INTEGER*4 variable which is assigned the number of the next record to be read or written on a direct-access file. If the file is connected but no data transfer has been done, Inri is assigned the value 1. If the file is not a direct-access file or if the position cannot be determined (possibly because of a previous error), Inri is undefined. BLANK=blnk 'blnk' is a character variable which is assigned the value 'NULL' if the BN edit-descriptor is the default for blank control and is assigned the value 'ZERO' if the BZ edit-descriptor is the default for blank control (see the OPEN statement and the chapter on "Format Specifications"). If the file is not connected or if the file is connected but not for formatted input-output, 'blnk' is undefined. The INQUIRE statement never returns an error condition. The specifiers 'ex' (exists) and 'ad' (opened) always get defined. When a specifier is said to be "undefined" in the descriptions above, it means that certain of the specifiers are meaningless in certain contexts. For example, if the access method for a unit is SEQUENTI~L, the 'rcl' (record length) and Inri (next record) specifiers have no meaning, and are thus said to be undefined (in the context that a program should not be examining those specifiers in such a case). For example, to see if a file named statement: 'xyzzy' exists, use the INQUIRE(FILE='xyzzy', EXIST=L) The value of the LOGICAL*4 variable L is set to .TRUE. or .FALSE. depending upon the existence of that file. To see if UNIT 10 is currently OPEN, use: INQUIRE (UNIT=lO, OPENED=L) Page 94 FORTRAN Reference Manual Chapter 10 10.5 Input and Output List Directed Input and Output List-directed input-output serves to process formatted records without the use of a FORMAT statement. Values in the records are in a "free-form". List-directed input-output is convenient for those cases where the precise layout of the data is not important. 10.5.1 List Directed READ The elements in the list-directed READ statement are the same as those for the READ statement previously described, with the exception that an asterisk character "*" is supplied as the format specifier. Data is read into storage locations as specified in the 'iolist'. Input data consists of a number of values and value separators. The next paragraph describes value separators--and the following paragraph describes values. 10.5.1.1 List Directed Value Separators Value separators are used to delimit values in a list-directed input list. A value separator is one of the following: a comma, with optional spaces on either side. a slash, with optional spaces on each side. one or more contiguous spaces between constants or last constant in the list. after the end-of-record, which appears as a space between two constants. A comma is used to separate values. cate a null value. Two commas in a row A slash has the effect that the remalnlng items in input iist are discarded and null values substituted. A value separator adjacent to sidered to be a null value. 10.5.1.2 an end-of-record is indiin not the con- List Directed Input Values A value is a constant, a null forms: FORTRAN Reference Manual (empty) value or one of the Page 95 Chapter 10 Input and Output r*c r* where 'r' is a repeat factor which must be an unsigned non-zero integer constant. The form of 'r*c' represents 'r' successive appearances of the constant 'ct. The form 'r*' is th~ same as 'r' successive null values. Neither of these forms may contain embedded spaces except where 'c' is a character constant. Individual values in list-directed input are in the forms described below. Values may not have embedded spaces, except character constants, where a space stands for itself. The acceptable forms of input values are: Null A null value is indicated by the presence of two contiguous value separators, no characters or spaces preceding the first value separator in an input list, or by an 'r·' form. A null value cannot be used as the real or imaginary part of a complex constant but can be used as an entire complex constant. List items which are null have no effect on the definition status of variables in the corresponding 'iolist'. Variables in the 'iolist' which are already defined stay defined and variables which are not defined stay undefined. Integers Must be the same form as for integer constants. Real Numbers Any valid format for a FORTRAN real number. Furthermore the decimal point can be omitted from a real number, in which case the number is assumed not to have a fractional part. Complex Numbers A complex value is represented by an ordered pair of real numbers in the format described above for real numbers. The pair of reals are separated from each other by a comma, and enclosed in parentheses. There can be spaces surrounding the numbers. An end of record can appear before or after the comma in a complex number. Character string values A string of characters enclosed in apostrophes. Embedded spaces are significant and are part of the constant. An apostrophe is represented by two juxtaposed apostrophes in the string. Character constants can span record boundaries. A record boundary in a character constant does not generate any gratuitous characters in the value. Character constants can be continued over as many Page 96 FORTRAN Reference Manual Chapter 10 Input and Output records as needed. Note that unterminated character constants can lead to disastrous results. If the character constant as read is longer than the length of the corresponding 'iolist' item, it is truncated to fit. If the character constant is shorter than the corresponding 'iolist' item, it is placed left justified in the variable and the remaining positions in the variable are filled with spaces. Logical values 10.5.2 Logical values are represented by a T (.TRUE.) or an F (.FALSE.). An optional period character "." may appear before the T or F character. The T or F can be followed by optional characters, but these characters must not be value separators slashes or commas. List Directed WRITE and PRINT The list-directed WRITE and PRINT statements are similar to the formatted WRITE and PRINT statements described previously, with the exception that the FORMAT specifier is a *. Data is transferred from the variables specified by the 'iolist' to the specified unit. In general, values are written on the output device in a manner consistent with list-directed input, but there are exceptions, the most notable being that character string data written out by a list-directed WRITE or PRINT statement cannot be re-read by a list directed input statement. FORTRAN starts new records when necessary. Values in the output are separated by three spaces, except that character values are not preceded or followed by any spaces. FORTRAN never generates slashes or null values on list-directed output. The forms of the different data types are as follows: Integer values are generated as for an Iv edit-descriptor. 'w' is the minimum number of characters required to print the integer value. Real and Double Precision are generated with the effect of either an F edit-descriptor or an E edit-descriptor, depending on the magnitude of the numbers involved. The specific edit-descriptors used are as described in the table below. FORTRAN Reference Manual Page 97 Input and Output Chap~er 10 +------------------+------------------------------+ Range of Number I Edit-Descriptor Used I I Real I Double Precision +------------------+-----------+------------------+ 11.0 < val < 10.0 I OPP9.6 I OPP17.l4 I +------------------+-----------+------------------+ I ~:~ : io~oor I lPBl3.6B2 I IPB22.14E3 I +------------------+-----------+------------------+ I Not A Number 1'1111111' I '1111111' I +------------------+-----------+------------------+ Plus Infinity I '+++++++' I '+++++++' I I Minus Infinity ,-------, ,-------, +------------------+-----------+------------------+ Complex numbers are generated as a pair of real numbers enclosed in parentheses with a comma separating the real and imaginary parts. Character string values are generated as strings of characters. However, character constants are not surrounded by apostrophes, meaning that they cannot be read back in using list-directed input. Logical values Page 98 are generated as T for .TRUE. and P for .FALSE. FORTRAN Reference Manual Format Specifications Chapter 11 Chapter 11 - Format Specifications This chapter describes formatted input-output and the FORMAT statements available from FORTRAN. The reader is assumed to be familiar with the FORTRAN file system, units, records, access methods and input-output statements as described in the previous chapter. A format specification is used in conjunction with formatted input-output to supply information which directs the editing or conversion between the internal representations of the machine and the representations of character strings in a file or character data item. 11.1 FORMAT Specifications and the FORMAT Statement If a READ, WRITE or PRINT statement specifies a format, it is considered to be a formatted input-output statement as opposed to an unformatted input-output statement. To reiterate what was described in the previous chapter, a format can be specified by any of the following forms: giving the label of a FORMAT statement, the name of an integer variable containing the label of a FORMAT statement, a character variable, character array element or character expression which ha~ the correct form of a format specifier, an asterisk character, "*", output. indicating list-directed input- The following examples illustrate valid ways to specify a mat: FORTRAN Reference Manual for- Page 99 Format Specifications * * * * * * * Chapter 11 Example the first reference to a FORMAT statement WRITE(*, 990) IGOR, JOHANN, KLUTZ 990 FORMAT(2I5, Il) Example the second ••••• assigned FORMAT label to integer ASSIGN 880 TO MORFAT , 880 FORMAT(2I5, Il) WRITE(*, MORFAT) IVAN, JANUS, KLONG * * * * * * * * * * * * Example the third using a character variable CHARACTER*9 FORCH FORCH ~ '(215, Il)' WRITE(*, FORCH) IVOR, JACKO, KELP Example the fourth ••••. using a character expression CHARACTER*7 CHAREX DATA CHAREX 1'215, Il'l WRITE(*, '(' II CHAREX II I)') IRENE, JANET, KLARG Example the fifth ••••• List-directed write WRITE(*, *) INEZ, JACKIE, KRON The format specification itself must begin with a parenthesis "C" and must end with a right parenthesis H)". acters after a matching right parenthesis are ignored. left Char- A FORMAT statement must have a label. Like all non-executable statements, a FORMAT statement may not be the target of a branching statement. Between the "C" and ")" characters, the format specifications appear. The format specifications are a list of items, separated by commas. Each of the items ~n the format list is one of: [rl ed repeatable edit-descriptors. ned non-repeatable edit-descriptors. [r) fs a nested format specification. At most ten levels of nested parentheses are allowed within the outermost level. where Ir' is an optional, Page 100 non-zero, unsigned integer constant FORTRAN Reference Manual Format Specifications Chapter 11 called a repeat specification. The comma separating two list items may be omitted if the resulting format is unambiguous, such as after a P edit-descriptor or before or after a / editdescriptor. The repeatable below) are: edit-descriptors Xv and Iv •• Fv.d Bv.d and Bv.dEe OW.d Gv.d and Gv.dEe Lv A and Av for for for for for for for (described in more detail Integer editing Real editing Real editing Real editing Real editing Logical editing Character-editing The wand e are unsigned non-zero integer and ~ are unsigned integer constants. constants. The non-repeatable edit-descriptors (also described below) are: The in 2 detail 'xxxxxxx' apostrophe editing nBxxxxxxxxxxxx Hollerith editing Te, TLe and TRe Tabbin~ to column nX insertlng spaces / starting a new record \ or $ inhibits starting new record conditionally terminates format list S, SS and SP optional Sign control Scale factor editing kP Blank control BN and BZ x is one of the characters from the character set that FORTRAN supports. nand c are unsigned, non zero integer constants. k is an optionally sIgned integer constant. Note that the FORTRAN compiler performs as much checking of FORMAT statements as is possible at compilation time. There can however, be incorrect FORMAT statements which the compiler cannot detect, and such incorrect statements will not manifest themselves until the program is actually run. 11.2 Interaction Between Format Specifications and I/O List Before going into the full details of how the various editdescriptors control the editing, it is necessary to describe how the format specification interacts with the input-output list ('iolist') in a given READ, WRITE or PRINT statement. If an 'iolist' contains any edit-descriptor must appear FORTRAN Reference Manual items, at least one repeatable in the format specification. In Page 101 Format Specifications Chapter 11 particular, the empty edit specification "()" may only be used if there are no items in the 'iolist', in which case the only action the input-output statement performs is the implicit record skipping action associated with formatted input-output. Each item in the 'iolist' is associated in turn, with a repeatable editdescriptor during the execution of the input-output statement. In contrast, the remaining non-repeatable format-control items interact directly with the record and are not associated with items in the 'iolist'. Items in a format specification are interpreted from left to right. Repeatable edit-des6riptors act as if they were present 'r' times - if 'r' is omitted it is treated as a repeat factor of 1. Similarly, a nested format specification is treated as if its list of items appears Ir' times. Format specifications are interpreted at execution time. The term "format controller" is used here to describe the entity that interprets the list. The formatted input-output process proceeds as follows: The format controller scans the format items in the order noted above. When a repeatable edit-descriptor is found, either: a corresponding item appears in the 'iolist'. In this case the item and the edit-descriptor are associated and input or output of that item proceeds under format control of the edit-descriptor, or: the format controller terminates the input-output process. If the format controller encounters a colon edit-descriptor, ":" in the format list and there are no further items in the 'iolist', the format controller terminates input-output. If the format controller encounters the matching final ")" of the format specification and there are no further items in the 'iolist', the format controller terminates input-output. If there are further items in the 'iolist', the file is positioned at the beginning of the next record and the format controller continues by re-scanning the format, starting at the beginning of the format specification terminated by the last preceding right parenthesis. If there is no such preceding right parenthesis, the format controller re-scans the format from the beginning. Within the portion of the re-scanned format, there must be at least one repeatable edit-descriptor. Should the re-scan of the format specification begin with a repeated, nested, format specification, the repeat factor indicates the number of times to repeat that nested format specification. The re-scan does not change the previously set scale-factor, BN or BZ blank control or S, SP or SS sign control. Page 102 FORTRAN Reference Manual Chapter 11 Format Specifications When the format controller terminates, the remaining characters of an input record are skipped or an end-of-record is written on output, except as noted under the \ or $ edit-descriptors. 11.3 Edit Descriptors Edit-descriptors are used to specify a field of a record. A detailed description of the various edit-descriptors follows. The repeatable edit-descriptors appear first, followed by the non-repeatable edit-descriptors. 11.3.1 Repeatable Edit Descriptors Repeatable edit-descriptors are associated with items from an 'io1ist l • Repeatable edit-descriptors are concerned with the editing of numeric, logical, and character data items. These are described in the paragraphs to follow. 11.3.1.1 Numeric Editing The I, S, F and G edit-descriptors are used for formatting integer, real and complex data. The following general rules apply to all of those edit-descriptors: On input, leading spaces are not significant. Other spaces are interpreted differently depending on the BN or BZ flag in effect, but all blank fields are always treated as "the value zero (0). Plus signs are optional. On input, with E and F editing, an explicit decimal point appearing in the input field overrides position of the decimal point as specified in the edit-descriptor. On output, generated characters are right field with leading spaces if required. justified in the On output, if the number of characters produced exceeds the field width, or the exponent exceeds its specified width, the entire field is filled with asterisks, but also see the next list item, concerning infinite and indeterminate values. On output, a value of plus infinity fills the field with plus signs, a value of minus infinity fills the field with minus signs, and an indeterminate value fills the field with question marks. . Editing of complex numbers is controlled by two E, F or G edit-descriptors in succession, each of which controls the editing of "ha1f of the complex value. The two editdescriptors for a given complex number do not have to be the ft FORTRAN Reference Manual Page 103 Chapter 11 Format Specifications same. 11.3.1.2 I - Integer Editing The edit-descriptor Iv must be associated with an 'iolist' item which is of type INTEGER (which is the same as INTEGER*4), INTEGER*l or INTEGER*2. The field width is 'we characters long. On input, an optional sign may appear in the field. The Iv •• edit-descriptor specifies the field width 'we as above, but the em' part specifies a minimum field width for the integer value. On input, the 'me specification has no effect. On output, if the converted integer is shorter than 'm' characters, leading zeros are placed in the field. If em' is zero and the integer value to be formatted is also zero, the output field consists of 'w' spaces, regardless of any sign control in effect (see later). 'm' must not be greater than 'W'g 11.3.1.3 F - Real Editing The edit-descriptor Fv.d must be associated with· an 'iolist' item which is of type real, double-precision or one half of a complex number. The width of the field is 'w' characters. The fractional part is 'de digits long. The input field begins with an optional sign, followed by a string of digits optionally containing a decimal point. If the decimal point is present, it overrides the 'de specified in the edit-descriptor. If the decimal point is not present, the rightmost 'de digits of the string are interpreted as following the decimal point - leading spaces are converted to zeros if necessary. The number may be followed by an optional exponent which is either of the forms: plus or minus followed by an integer, or E or D, followed by zero or more spaces, followed by an optional sign, followed by an integer. Band D are treated identically. The output field occupies 'w' digits, Ide of which follow the decimal point. The output value is controlled both by the 'iolist' item and by the current scale-factor (see the paragraph later, on "Scale Factor Editing", in the discussion on nonrepeatable edit-descriptors). The output value is rounded, not truncated. Page 104 FORTRAN Reference Manual Chapter 11 11.3.1.4 Format Specifications E and D - Real Editing The B or D edit-descriptors control formatting of real elements. These edit-descriptors must be associated with an 'iolist' item which is of type real, double-precision or one half of a complex number. An a or D edit-descriptor takes one of the forms aw.d, Dw.d or Bw.dEe. The forms Ew.d and Dw.d have identical editing effects. In each case, the field width is 'w' characters. The 'e' has no effect on input. The input field for an a edit-descriptor is identical to that described by an P edi~ descriptor which has the same 'w' and 'd' fields. The form of the output field depends on the scale-factor (set by the P edit-descriptor) in effect. For a scale-factor of 0, the output field contains a minus sign (if needed), followed by a decimal point, followed by a string of digits, followed by an exponent field for an exponent 'exp' of one of the following forms: Ew.d -99 <= 'exp' <= 99 H, followed by plus or minus, two digit exponent. followed by the Ew.d -999 <= 'exp' <= 999 plus or minus, followed by three digit exponent. Ew.dEe -lOe- l <= 'exp' <= 10e- l a, followed by plus or minus, followed by 'e' digits of exponent with possible leading zeros. The form Bw.d must not be used if the exponent to be printed exceeds 999. absolute value of the The scale-factor controls decimal normalization of the printed 'E' field. If the scale-factor 'k' is in the range -d < k <= 0, the output field contains exactly 'd'-'k' leading zeros after the decimal point and 'd'+'k' significant digits after that. If 0 < k < d+2, the output field contains exactly 'k' significant digits before the decimal point and 'd'-'k'-l places after the decimal point. Other values of 'k' are errors. 11.3.1.5 G - Real Editing The G edit-descriptor descriptors except that "adaptable" output format FORTRAN Reference Manual is similar to the E and P editthe G edit-descriptor provides for an depending on the magnitude of the Page 105 Chapter 11 Format Specifications number being converted - it gives the user a flexible choice of output formats without the need to pre-check on the size of the numbers ahead of time. The G edit-descriptor must be associated with an 'iolist' item which is of type real, double-precision or one half of a complex number. The G edit-descriptor takes one of the forms Gw.d or Gw.dBe. In either case, the final output field width is 'Wi characters. The number of digits after the decimal point is 'd' digits unless a scale-factor greater than 1 is in effect. On input, G editing acts the same as F editing (see above). On output, the format of the converted number is dependent on its magnitude. If N is the number to be converted, the table below describes the action of the G edit-descriptor: +---------------------------+--------------------------------+ I Magnitude of N I Equivalent Conversion I +---------------------------+--------------------------------+ N < 0.1 or Gw.d is the same as kPBw.d N > 10**d Gw.dEe is the same as kPEw.dEe +---------------------------+--------------------------------+ 0.1 < N < 1 F(w-n) .d, n(Ib') I I I 1 < N < 10 F(w-n).(d-l), n('b l 10**(d-2) < N < 10**(d-l) F(w-n) .1, n('b') ) 10**(d-1) < N < 10**d F(w-n) .0, n('b') +---------------------------+--------------------------------+ where 'b' stands for a blank (space) in the above table, and is 4 for Gw.d editing and 'e'+2 for Gw.dEe editing. 11.3.1.6 'n' Formatting Extreme Values The floating point system used in SVS FORTRAN contains several extreme value representations. These are infinity, both positive and negative, and Not a Number, call NaN. Infinities are produced by floating-poInt overflow and NaN's are produced by certain invalid operations such as zero ~ivided by zero. When extreme values are printed in either D, E, F or G format, they are represented by replacing all digits in the field with either plus signs '+++.+++' for positive infinity, minus signs '---.---' for negative infinity, or question marks '111.111' for NaN. Page 106 FORTRAN Reference Manual Chapter 11 11.3.1.7 Format Specifications L - Logical Editing The edit-descriptor for a logical item is Lw, indicating that the field width is 'Wi characters. The 'iolist' element associated with an L edit-descriptor must be of type LOGICAL (which is the same as LOGICAL*4), ·LOGICAL*l or LOGICAL*2. On input, the field consists of optional spaces, followed by an optional decimal point, followed by a T (for .TRUE.) or P (for .FALSE.). Any further characters in the field are ignored but accepted on input, so that the strings .TRUE. and .FALSE. a.re valid inputs. or On output, 'w'-l spaces are followed by either the character P as·appropriate. 11.3.1.8 T A - Character Editing The forms of the Aw. The straight from the number of ated with. The associated with an edit-descriptor for character items are A or A format acquires an implied field width, 'Wi, characters in the 'iolist' item it is associ'io1ist' item must be of type character to be A or Awedit-descriptor. On input, if 'w' equals or exceeds the number of characters. in the 'io1ist' element, the rightmost characters of the input field are used as the input characters, otherwise the input characters are left-justified in the input 'io1ist' item, and trailing spaces are added. On output, if 'w' exceeds the characters produced by the 'io1ist' item, leading spaces are provided, otherwise the leftmost 'Wi characters of the 'iolist' item are output. It is also possible to read and write non-character items with the A edit-descriptor. When this is done, the variable is treated as if it were a CHARACTER variable whose length is the number of bytes that that variable occupies. 11.3.2 Non Repeatable Edit Descriptors Non-repeatable edit-descriptors are format list items which are not associated with any 'io1ist' items. 11.3.2.1 'xxx' - Apostrophe Editing APostro~he editing has the form of a character constant. It causes c aracters to be written from the enclosed characters, including spaces, of the edit-descriptor itself. Within the string, two ' signs in a row are interpreted as one apostrophe. FORTRAN Reference Manual Page 107 Chapter 11 Format Specifications Apostrophe edit-descriptors cannot be used on input. 11.3.2.2 H - Hollerith Editing The nB edit-descriptor (called Hollerith editing) transmits the In' characters (including spaces) following the descriptor to the output. Hollerith editing cannot be used for input. Examples of APostrophe and Hollerith Editing C C C C Each of the following WRITE statements writes the characters ASC'DEF to the output. C WRITE(*, 970) 970 FORMAT ( , ABC' 'OEF' ) C WRITE(*, C C • (' i ABC' • i , OEF' , ) , ) WRITE(*, , (7HASC' , OEF) , ) WRITE(*, 960) 960 FORMAT (7HABC'DEF) 11.3.2.3 X and T - positional Editing The X and T edit-descriptors described below have the effect of positioning the format controller within a record. They do not by themselves transmit any characters to or from a record. When a formatted record is read on input, it is treated as if it were of infinite length, with as many trailing spaces as needed to satisfy input requests. Positioning using the X and T edit-descriptors determines the position of the next character to be read from the record. These edit-descriptors may therefore be used to skip portions of the input record or to re-read the same positions in the record more than once. On output, it is as if the input-output system initially creates a record which is potentially of infinite length and filled with spaces. As formatted output transmits characters to the record, the final length of the record is determined by the rightmost position to which a character is transmittede Changing the pOSition with the X or T edit-descriptors does not directly affect the length of the record, but does affect the position at which the next character is transmitted to the output record. Using the X or T edit-descriptors, positions in the record may never have any characters transmitted to them (they are skipped), which means that those positions retain their original blank Page 108 FORTRAN Reference Manual Format Specifications Chapter 11 values, providing, of course, that characters are transmitted after the skipped positions so that those character positions are eventually included in the output record. It is also possible to overwrite positions of formatted output records using the X and T edit~descriptors by positioning to a place where data was previously written. In this case, only the last value written to a given character position becomes part of the final formatted record. nX edit-descriptor advances the record position by In' If In' is omitted, the value 1 is used. spaces. The Te, TLc and TRc edit-descriptors position the record to a specified column. The Tc edit-descriptor positions the record to absolute column position 'ct. The TLc edit-descriptor moves the column position to 'c' characters to the Left (backwards), relative to the current position. The TRc edit=descriptor moves the column position 'c' characters to the Right (forwards) relative to the current position. On input, the T edit-descriptors have the effect of skipping or allowing re-reading of portions of the input record. If the TLc edit-descriptor moves the character position to a place where input fields were previously transmitted, those i~ems can be retransmitted. On output, if a character is transmitted to a position where another character has already been transmitted, the earlier transmission is replaced. 11.3.2.4 Slash Editing - End of Transfer on Record The slash character current record. "I" indicates end of transfer on On input, the file is positioned to the beginning of record. th~ On output, an end-of-record is written and the tioned to write at the start of the next record. is 11.3.2.5 file the next posi- Backslash or Dollar Editing - Inhibit End of Record The backslash "\" and dollar "$" edit-descriptors when writing to the * device (the Standard Output). only apply Normally, when the format controller terminates a format list, data transmission to the current record ceases and the file is positioned so that a new WRITE starts a new record. If, while scanning the format list, the format controller finds a backslash character "\" or a dollar character "$", the automatic FORTRAN Reference Manual Page 109 Chapter 11 Format Specifications end-of-record action is inhibited. This means that subsequent input-output statements can continue reading from or writing to the sa~e recordo The most common use for this mechanism is to prompt to the Standard Input and read a response on the same line. For example: WRITE(*, • (A) ') 'Please type your weight -> ' READ(*, '(BN, 16)') LIGHT The backslash or dollar edit-descriptor does not inhibit the automatic end-of-record generated when reading from the * unit. Input from the Standard Input must always be terminated by a carriage-return. This permits proper functioning of the backspace and line-delete keys. 11.3.2.6 Colon Editing - Conditional Termination The : character appearing in a format list has the effect of terminating processing of the format list if there are no more items in the 'iolist'. If there are more items in the 'iolist' when the colon is encountered, the colon is ignored. There may be more than one colon in a format list. The colon edit-descriptor is useful for terminating extraneous textual data that might otherwise be printed after all appropriate numeric items have been transferred. It is also useful for preventing further / edit-descriptors on input. 11.3.2.7 P - Scale Factor Editing The kP edit-descriptor sets the scale-factor for subsequent B, F and G edit-descriptors until another kP edit-descriptor is encountered. At the start of each input-output statement, the scale-factor is zero CO). The scale-factor affects format editing as follows: On input with E, P or G editing, providing that an explicit exponent does not appear, the externally represented number is equal to the internally represented number multipled by lO**k. On input with E, P and G editing, the scale-factor has no effect if there is an explicit exponent in the input field. On output with B editing, the real part of the quantity is multiplied by 10**k and the exponent is reduced by 'k', effectively altering the column position of the decimal point, but not the actual output value. On output with P and G editing, the externally represented number is equal to the internally represented number multiplied by lO**k. Page 110 FORTRAN Reference Manual Chapter 11 11.3.2.8 Format Specifications BN and BZ - Blank Interpretation The DN and DZ edit-descriptors specify blanks (spaces) in numeric input fields. the interpretation of The initial setting of this edit-descriptor is dependent on the BLANK= parameter to the OPEN statement when this file was opened. See the OPEN statement for a description of the BLANK= parameter. If BZ editing is in effect, leading blanks are ignored and embedded blanks are treated as zeros. This edit-descriptor stays in effect until a BN edit-descriptor is encountered in the format list. If BN editing is in effect, blanks in subsequent input fields are ignored until a BZ edit-descriptor is processed. The effect of ignoring blanks is to treat all the non-blank characters in the input field as if they were right justified in the field, with the number of leading blanks equal to the number of ignored blanks. In the example below, the READ statement treats the characters shown between the vertical bars as the value 123, where the term indicates a carriage-return: READ(·, 100) 1 100 FORMAT(BN, 16) 123 1 456 123 123 1 123 \ Using the BN edit-descriptor in conjunction with the infinite blank padding at the end of formatted records makes interactive input very convenient. 11.3.2.9 S, SS and SP - Sign Control Editing An output field generated by I, D, E, P or G editing includes an optional sign immediately preceding the digits of the value. The sign always appears if the number is negative, but if the number is positive, FORTRAN omits the plus sign. At the start of a format list, FORTRAN opts to omit plus signs. An S, SS or SP edit-descriptor controls the option. Any option chosen remains in effect until another one is found in the format list. An SP format code specifies that "optional" plus signs are always printed. An SS edit-descriptor specifies that they are to be suppressed always. An S option restores FORTRAN's option to omit plus signs. FORTRAN Reference Manual Page 111 Format Specifications Chapter 11 On input, these format codes have no effect and are ignored. Page 112 FORTRAN Reference Manual Chapter 12 Program and Subprogram Structure Chapter 12 - Program and Subprogram Structure A complete executable FORTRAN program consists of the following elements: a main program, any number of SUBROUTINE subprograms, any number of FUNCTION subprograms, any number of BLOCK DATA subprograms. A subprogram is a program unit which begins with a SUBROUTINE, FUNCTION or BLOCK DATA statement. A subprogram is defined separately and can be compiled independently of the main program. Subroutine and function subprograms are procedures which can share values and results through argument lists, common blocks or both. A BLOCK DATA subprogram acts as a container for initializing common blocks. A procedure can be a subroutine, external function or statement-function. 12.1 function, intrinsic Main Program A main program is any program unit that does not start with a SUBROUTINE, FUNCTION or BLOCK DATA statement. A main program may start with a PROGRAM statement. Execution of a FORTRAN program starts with the first executable statement in a main program. Consequently there must be precisely one main program in every executable FORTRAN program. The form of a PROGRAM statement is: PROGRAM progname where 'progname' is a user-defined name of the main program. The name 'progname' is a global name. Therefore it must not be the same as the name of another external procedure or the name of a common block. The name 'progname' is also local to the main program and must not be the same as any other local name in the main program. The PROGRAM statement may only appear as the first FORTRAN Reference Manual Page 113 Chapter 12 Program and Subprogram Structure statement of a main program. Example of ! PROGRAM Statement PROGRAM 12.2 BESSEL Access To Command Line Arguments The SVS FORTRAN-77 system provides for access line which called up the running program. to the command The FORTRAN-77 run-time library contains two routines which enable a FORTRAN-77 program to access its command line arguments. IARGC (Argument Count) is an INTEGER FUNCTION which returns the number of arguments actually typed on the command line. GETARG is a subroutine which retu·rns a specified argument. definition of GETARG is: The SUBROUTINE GETARG(ARGNUM, ARGCH) INTEGER ARGNUM CHARACTER *(*) ARGCH ARGNUM is the number of the argument which is to be accessed from the command line. Arguments are numbered from 1 (not from o as on some operating systems). Indexing from 1 is done for compatibility with the Pascal numbering, and with FORTRAN-77's default lower array bounds. The value passed to ARGNUM must be in the range 1 through IARGC. If it is not, the results are undefined. Under some operating systems, the first argument is the name of the program. (argument 1) The receiving variable is treated just as it is in a character assignment statement in FORTRAN-77. If the source character string is shorter than the target variable, it is padded with spaces on the right. If the source character string is longer than the receiving variable, it is truncated. Rere is a short example of using the argument access to echo the command line to the standard output. Page 114 facility FORTRAN Reference Manual Chapter 12 Program and Subpr?gram Structure PROGRAM ECHO CHARACTER*100 ARG INTEGER I 200 12.3 00 200 I • 1, IARGC() CALL GETARG(I, ARG) WRITE(*, *) ARG END Formal Arguments and Actual Arguments This section covers the relationship between formal arguments and actual arguments in function and subroutine subprograms. Throughout the discussion, the terms "formal argument" and "dummy argument" are synonymous. A formal argument is the name (local to the subprogram) by which the argument is known during the execution of the subprogram. The actual argument is the actual value (variable, expression, array and so on) passed to the subprogram in question at the time a caller references the subprogram. There are a number of ways to pass values into and out of subprograms. One way is via common blocks. Another way is to use the argument mechanism of subroutines and functions. It is this second way that this section covers. Arguments are used to pass values into and out of subprograms. The number of actual arguments must be the same as the number of formal arguments. The types of the corresponding formal and actual arguments must also agree. 12.3.1 Argument Association On entry to a subroutine or function, the actual arguments become associated with the formal arguments. The association remains effective until execution of the subprogram terminates. Thus assigning a value to a formal argument while executing a subprogram can change the value of the corresponding actual argument. If an actual argument is a constant, function reference, or an expression other than a simple variable, assigning a value to the formal argument should not be done, and can lead to strange and hard to diagnose side effects. A formal argument that is a variable can be associated with an actual argument tha~ is a variable, an array element or an expression. The length attributes of integer and logical arguments must match exactly, that is, an actual argument of type INTEGER*2 must only be associated with a formal argument of FORTRAN Reference Manual Page 115 Program and Subprogram Structure Chapter 12 INTEGER*2. Actual arguments which are integer expressions must be associated with formal arguments of type INTEGER*4 or INTEGER*2 depending on the default integer size. Similarly, actual arguments which are logical expressions must only be associated with formal arguments of type LOGICAL*4 or LOGICAL*l depending on the default integer size. An "expression" in this context is any construct which is not a variable, array or array element. Actual arguments which are manifest constants, (i.e. names set to constant values in PARAMETER statements) are treated exactly as if the constant (a constant expression) were the actual parameter. Names set to constant values in PARAMETER statements do not become typed by their initial letter or otherwise except by the form of the constant expression to which they were set. Thus, actual arguments which are manifest constants will result in 4 byte values with the $INT2 option not set or 2 byte integer (1 byte logical) values with the $INT2 option set. If an actual argument is an expression (anything not a variable, array, or array element), it is evaluated immediately prior to the association of actual and formal arguments. If an actual argument is an array element, its subscript expression is evaluated just prior to the association and remains constant during execution of the subprogram, even if the subscript expression contains variables that are re-defined while the subprogram executes. A formal argument that is an array can be associated with an actual argument that is an array or an array element. The number and size of dimensions in the formal argument can differ from those of the actual argument, but any re~erence to the formal argument must be within the limits of the actual array's storage sequence. While the FORTRAN system cannot detect such an outof-bounds reference, the results are generally unpredictable and undesirable. A formal argument which is an asterisk character, ".", may only appear in the argument list of a subroutine or in an ENTRY statement in a subroutine. The actual argument is an alternate return specifier in the subroutine CALL statement (see below). Formal arguments which are arrays or character strings may have adjustable dimensions. This enables writing more general subprograms which can accept objects of varying size. A formal argument which is an array may have its dimensions specified by variables passed as actual arguments. This is an adjustable array. An array formal argument may also have the upper bound of its last dimension specified as an asterisk character, ".", which declares it to be an assumed size array. In this case, the value of that dimension is not passed as an actual argument, but is determined by the number of elements in the array. If an array Page 116 FORTRAN Reference Manual Program and Subprogram Structure Chapter 12 is dimensioned as *, it is the programmer's responsibility to ensure that the calling program unit has provided an array big enough to contain all the elements·stored into it in the subprogram. Character strings may have their length specified as (*). This declares the string to be of varying size. The length of the string is not passed explicitly as an argument, but is determined by the system from the length of the actual argument. A formal argument which is of type character must not .be greater than the length of the actual argument. If the length of the actual argument is greater than that of the formal argument, the actual argument is truncated on the right. If a formal argument is of type character whose length is specified as (*), a character expression involving concatenation of that argument must not be used as an actual argument to any other procedure, format specification or input-output list in an input-output statement. 12.4 Subroutines A subroutine is a program unit that is called from other program units via the CALL statement. When inVOked, the subroutine performs the actions that its executable statements define, and then returns control to the program unit that called it. A subroutine does not directly return a value, although values can be passed to the caller via the subroutine's arguments or via common variables. 12.4.1 SUBROUTINE Statement A subroutine starts with a SUBROUTINE statement and ends with the first END statement that follows. A subroutine can contain any kind of statement except a PROGRAM statement, a FUNCTION statement or a BLOCK DATA statement. The form of a SUBROUTINE statement is: . SUBROUTINE subname [ ( farg [r farg] ••. ) ] 'subname' is the user-defined name of the subroutine. 'farg' is a formal argument specification. A formal argument can be the user-defined name of a variable, array, dummy procedure, or it can be an alternate-return specifier designated by the asterisk character n*" The subroutine name 'subname' is a global name. It is also local to the subroutine it names. The list of argument names FORTRAN Reference Manual Page 117 Program and Subprogram Structure Ghapter 12 defines the number (and with any subsequent IMPLICIT, type or DIMENSION statements) the type of arguments to that subroutine. Argument names must not appear in COMMON, DATA, EQUIVALENCE or INTRINSIC statements. I f a subro·utine does not have any formal arguments, an empty argument list indicated by a pair of parentheses may follow the name, as shown in the examples below. Examples of SUBROUTINE Statements SUBROUTINE NOARGS SUBROUTINE ZILCH() SUBROUTINE ONEARG (RILEY) SUBROUTINE ALTRET(LIMIT, *) 12.4.2 CALL Statement A subroutine is executed when a CALL statement in another subprogram references that subroutines by name. The form of a CALL statement is: CALL subname [ ( [arg (, arg] ••• ) ) ) 'subname' is the name of the subroutine to call. 'arg' is an actual argument. described below. The actual arguments are The actual arguments in the CALL statement must agree in type and number with the corresponding formal arguments specified in the SUBROUTINE statement of the referenced subroutine. Actual arguments may be one of the following: An expression, An array name, An intrinsic function name, An external procedure name, A dummy procedure name, An alternate-return specifier of the form *s, where IS' is the statement-label of an executable statement in the same program unit as the CALL statement. Page 118 FORTRAN Reference Manual Program and Subprogram Structure Chapter 12 If there are no arguments in the SUBROUTINE statement, a CALL statement that references that subroutine must not have any actual arguments. A pair of parentheses following the subroutine name is optional in the CALL statement. A formal argument can be used as an actual argument in another subroutine call. Execution of a CALL statement proceeds as follows: 1. All actual arguments that are expressions are evaluated. 2. All actual arguments are then corresponding formal arguments. 3. The body of the specified subroutine is executed. 4. Control is returned to the subroutine's caller when a RETURN or and END statement is executed in the subprogram, either at the statement following the CALL statement, or at the alternate return specifier designated in a RETURN statement. associated with- their A subroutine specified in any program unit can be called from any other subprogram within the same executable program. Recursive subroutine calls are not allowed in FORTRAN. That is, a subroutine cannot call itself directly, nor ~ay a subroutine called by the current subroutine subsequently call the current subroutine. 12.5 Functions A function is referenced in the context of an expression and returns a value that is used in the evaluation of that expression. There are three kinds of functions, namely: external functions, intrinsic functions and statement functions. The subsections to follow describe the three kinds of functions. A function reference can appear in an expression. Referencing a function in the context of an expression causes that function to be executed. The resulting value that the function returns is used as an operand in the expression that references the function. The form of a function reference is: funcname ([arg [, arg]... ] ) 'funcname' is the name of an external, intrinsic, or ment function. larg' is an actual argument to the function. The forms of the actual arguments are described below. state- The number of actual arguments must be the same as the number of formal arguments. Except for generic intrinsic functions, the types of the actual arguments must agree with the types of the FORTRAN Reference Manual Page 119 Program and Subprogram Structure Chapter 12 corresponding formal arguments. An actual argument can be anyone of: An expression, An array name, An external procedure name, An intrinsic function name, A dummy procedure name. 12.5.1 External Functions An external function is specified by a function subprogram. It starts with a FUNCTION statement and ends with an END statement. A function can contain any kind of statement except a SUBROUTINE statement, PROGRAM statement or BLOCK DATA statement. The form of a FUNCTION statement is: (type]· FUNCTION function_name ( (farg (, farg] ••• ] ) 'type' defines the return type of the function. 'type' is one of INTEGER, INTEGER*l~ INTEGER*2, INTEGER*4, REAL, REAL*4, REAL*B, DOUBLE PRECISION, CHARACTER [*len] , LOGICAL, LOGICAL·l, LOGICAL*2, LOGICAL*4 or COMPLEX. 'function~name' is the user-defined name of the function. 'farg' is a user-defined name of the formal argument. The function name 'function name' is a global name. It must not be the same as the name of any other PROGRAM, SUBROUTINE, FUNCTION or BLOCK DATA subprogram. The function name is also local to the function it names. If the 'type' specification is omitted from the function declaration, the function's type is determined by default and any subsequent IMPLICIT statements that would determine the type of an ordinary variable. If the 'type' specifier is present, the function name must not appear in any subsequent type statements. The list of argument names determines the number (and with any subsequent IMPLICIT, type or DIMENSION statements) the type of the arguments to the function. Neither the argument names nor the function name may appear in any COMMON, DATA, EQUIVALENCE or INTRINSIC statements. The function name must appear as a variable in the subprogram that defines the function. Each execution of the function must Page 120 FORTRAN Reference Manual Chapter 12 Program and Subprogram Structure assign a value to that variable. The final value of this variable upon execution of a RETURN or END statement, defines the value of the function. After this variable is defined, its value can be referenced in an expression just like any other variable. In addition to the value returned, an external function can return values via as~ignment to one or more of its formal arguments or through variables in common areas. A function which is declared as type CHARACTER*(*) derives its length from the specification (declaration) of the function in the calling program unit. 12.5.2 Intrinsic Functions Intrinsic functions are those functions that the FORTRAN compiler pre-defines. Intrinsic functions are available for use in a FORTRAN program. The table in the appendix on "Intrinsic Functions" gives the name, definition, number of arguments, and type of the intrinsic functions available in SVS FORTRAN-77. Those intrinsic functions which accept several types of arguments must have all those arguments of the same type in any given reference. An intrinsic function can appear in an INTRINSIC statement, but only those intrinsic functions listed in the table in the appendix on "Intrinsic Functions" may do so. An intrinsic function may also appear in a type statement, but only if the type is the same as the standard type of that intrinsic function. Certain intrinsic functions limit the range of their arguments in certain ways determined by the definition of the function being computed. For example, the logarithm of a negative number is mathematically undefined, and is therefore not allowed. 12.5.3 Statement Functions A statement-function is a function that is defined by a single statement. It is similar in form to an assignment statement. A statement-function statement must appear in a subprogram after any specification statements and before any executable statements. A statement-function statement is not executable - rather the body of the statement-function statement serves to define the meaning of the statement-function. A statement-function is executed (in the body of the subprogram in which it is defined) by referencing it just like a function. The form of a statement-function statement is: function_name ( [arg [, arg) ••• ] ) = expression 'function name' is the name defined. FORTRAN Reference Manual of the statement-function being Page 121 Chapter 12 Program and Subprogram Structure name of the formal 'arg' is the user-defined argument(s), if any. 'expression' is an expression that defines how the formal arguments are to be combined to generate a function result when the function is referenced. The type of the 'expression' must be assignment compatible with the type of the statement-function name. The list of formal argument names serves to define the number and types of arguments to the statement-function. The scope of the formal arguments is the statement-function. Therefore the formal argument names may be used as other user-defined names in the rest of the program unit that contains the statement-function statement. The name of the statement-function is local to the containing program unit, and therefore must not be used for any other purpose, other than as the name of a common block, or as the name of a formal argument to another statement-function statement. The type of all such other uses must be the same. If a formal argument to a statement-function statement is the same as a local name in the program unit, a reference to that name within the statementfunction always refers to the formal argument, never to the other usage. Within the 'expression', references to variables, formal arguments of the containing subprogram, other functions; array elements and constants, are all allowed. Statement-function references, however, must refer to statement-functions defined prior to the statement-function in which they appear. Statementfunctions must not be called recursively, either directly or indirectly. A statement-function can only be referenced in the subprogram in which it is defined. A statement-function name must not appear in any specification statement other than a type statement or a COMMON statement. If a statement-function name appears in a type statement, that name must not be defined as an array name. If a statement~function name appears in a COMMON statement, that name can only be the name of the common area. 12.6 ENTRY Statement A subroutine or function subprogram has a primary entry-point which is established via the SUBROUTINE or FUNCTION statement which declares that program unit. A subroutine call or a function reference normally activates that subprogram at its primary entry-point, and the first statement which is executed is normally the first executable statement in the subprogram. It is possible, however, to define alternate entry-points in a subroutine or function subprogram. These alternate entry-points are the start of sequences of statements which are different from Page 122 FORTRAN Reference Manual Program and Subprogram Structure Chapter 12 the sequence executed by entering the subprogram at its primary entry-point. In addition, such alternate entry-points can have formal argument lists which differ in number and type from those found in the primary entry-point, and from those of other ENTRY statements in the same subprogram. The format of the ENTRY statement is: ENTRY entname [ ( farg [, farg] ••• ) ] 'entname' is the user-defined name of the entry-point the subroutine or function subprogram. for 'farge is a formal argument specification. A formal argument can be the user-defined name ~f a variable, array, dummy procedure, or, if the subprogram is a subr~utine subprogram, it can be an alternate-return specifier designated by the asterisk character "*". The entry-point name 'entname' is a global name. It is also local to the subprogram in which it appears. The list of argument names defines the number (and with any IMPLICIT, type or DIMENSION statements) the type of arguments to that subroutine. Argument names must not appear in COMMON, DATA, EQUIVALENCE or INTRINSIC statements. If the entry-point name, 'entname' is in a function subprogram, the name can appear in a type statement. An ENTRY statement must not appear within the block or a DO block. body of an IF As with SUBROUTINE and FUNCTION statements, if there are no arguments to the ENTRY statement, an empty argument list can be supplied. When a subprogram is referenced or called via an alternate entry-point, the actual arguments must agree in number, order and type with the formal arguments (except for subroutine names and alternate return specifiers which do not have a type). 12.6.1 Restrictions on the ENTRY Statement An entry name must not appear as a dummy argument in a FUNCTION, SUBROUTINE or another ENTRY statement, and must not appear in an EXTERNAL statement. In a function subprogram, the only place the entry-point name may be used prior to the ENTRY statement is in a type statement. to If a function subprogram is of type character, all entry-points that function must also be of type character. If the length FORTRAN Reference Manual Page 123 Program and Subprogram Structure Chapter 12 of the character function is specified as (*), all entry-points to that function must also have a length of (*), otherwise all entry-points must have the same length specification. An argument in an ENTRY statement cannot appear prior ENTRY statement unlp.ss it: to that is either a type statement, is an argument in the SUBROUTINE or FUNCTION statement which begins the procedure containing the ENTRY statement, appears in a prior ENTRY statement in the same procedure. 12.1 RETURN Statement A RETURN statement returns control from a subprogram to the program unit which called it. A RETURN statement can only appear in a function or subroutine subprograms The form of a RETURN in a function subprogram is: RETURN The form of a RETURN· statement in a subroutine subprogram is: RETURN (!.] Where the optional!. is an integer expression. Execution of a RETURN statement terminates the execution of the containing function or subroutine subprogram. If the RETURN statement is in a function subprogram, the value of the function is the current value of the variable with the same name as the function. If the function variable has not been assigned to prior to executing a RETURN or an END statement, the function value is undefined. The RETURN statement is optional in a subprograms Executing an END statement is equivalent to executing a RETURN statement. . If e is supplied on the RETURN statement, it indicates an alternate return from the subroutine. If e lies between 1 and 'n', where 'n' is the number of asterisks in the SUBROUTINE or ENTRY statement, the value of e selects the e'th asterisk from the formal argument list. ControT then returns-to the caller at the label specified by the !.'th alternate return specifier. If e is omitted, or if e lies outside the range 1 to 'n', the effect is to execute a-normal return. Control then returns to the caller at the statement after the CALL statement that invoked the current subroutine. Page 124 FORTRAN Reference Manual Chapter 12 12.8 Program and Subprogram Structure Definition Status When a RETURN statement or an END statement is executed in a subprogram, all objects within the subprogram become undefined, with the following exceptions: Objects specified by SAVE statements. Objects in blank common. Anything in a named common block that appears in the current subprogram and also appears in at least one other subprogram that directly or indirectly references the current subprogram. Initially-defined objects that have nor become undefined. neither been re-defined If a named common block appears in the main program, in that common block does not become undefined. 12.9 anything BLOCK DATA Subprogram A BLOCK DATA subprogram is a non-executable subprogram which is used to initialize the values of variables and array elements in named common areas. There may be more than one block data subprogram in a FORTRAN program, but if there is more than one block data subprogram, only one of them can be un-named. The for.mat of a BLOCK DATA statement is: BLOCK DATA [blockname] where 'blockname' is the optional name of the block data gram. subpro- The BLOCK DATA statement must appear as the first statement of the block data subprogram. The name, 'blockname', if present, must not be the same as any the name of any any external procedure, main program, common area or other block data subprogram. The name, 'blockname' must not be the same as any local name in the subprogram. A block data subprogram can contain type statements, IMPLICIT, PARAMETER, DIMENSION, COMMON, SAVE, EQUIVALENCE or DATA statements. A block data subprogram ends with an END statement. More than one named common block can be initialized in the same block data subprogram. All the variables in a given named common block must be specified, even if they are not all initialized. A given named common block may only be specified in data subprogram in the same executable program. FORTRAN Reference Manual one block Page 125 Chapter 12 Program and Subprogram Structure Examples of BLOCK DATA Subprogram BLOCK DATA • * Whammo Declare a cornmon block with variables • COMMON /DRINKS/ REAL Beer COMPLEX Wine DOUBLE PRECISION • • • Beer, Wine, Scotch Scotch Declare another common block with variables COMMON /FOODS/ LOGICAL Burger REAL Dogs COMPLEX Fries • • Burger, Dogs, Fries Now initialize some of the variables. • • DATA Beer /3.2/, Wine /(11.5, 1.5)/ DATA Burger /.TRUE./, Fries /(1.1, 2.8)/ END In the example above, note that not all the variables were initialized~ 12.10 The FORTRAN Intrinsic Functions Intrinsic functions are those system supplied ("built-in") functions which are otherwise difficult to express in FORTRAN. An intrinsic function is supplied by FORTRAN. An intrinsic function returns a single value and is referenced in the same way as a user-defined function. If a variable, array or statement-function is defined with the same name as that of an intrinsic function, the name is local to the program unit in which it is declared and the intrinsic function of that name is no longer available to that program unit. If a function subprogram is defined which has the same name as that of an intrinsic function, use of that name references the intrinsic function, unless the name is declared as the name of an external function via the EXTERNAL statement. Certain intrinsic functions are generic. In general, if a generic name exists, a generic name can be used in place of a specific name and permits greater flexibility than a specific name. Except for the type conversion functions, the type of the Page 126 FORTRAN Reference Manual Chapter 12 Program and Subprogram Structure argument to a generic function determines the type of the result. For example, the generic function LOG computes the natural logarithm of its argument, which may be real, double precision or complex. The type of the result is the same as the type of its argument. The specific functions ALOG, DLOG and CLOG also compute the natural logarithm. ALOG computes the log of a real argument and returns a real result. Likewise, DLOG and CLOG accept double precision and complex arguments and return double precision and complex results, respectively. Only the specific name can be used as an actual argument when an intrinsic function name is passed to a user-defined procedure or function. The table in the appendix, "FORTRAN Intrinsic Functions", shows the intrinsic functions, their generic and specific names, their number of arguments and their argument types and result types. FORTRAN Reference Manual Page 127 Program and Subprogram Structure Page 128 Chapter 12 FORTRAN Reference Manual FORTRAN Compile Time Options Chapter 13 Chapter 13 - FORTRAN Compile Time Options Compiler Directives are a SVS extension to ANSI FORTRAN. SVS FORTRAN comp11er d1rectives provide additional controls over the compiler's actions. A compiler directive line is a line with a dollar sign $ in column one. A compiler directive line can appear anywhere that a comment line can appear. Spaces are significant in compiler directive lines, where they delimit keywords and filenames. Some of the compiler directives listed FORTRAN-77 cater to FORTRAN-66 features. 13.1 below are to make $INCLUDE - Include Source File $INCLUDE filename the file specified by "filename" is textually included in the program source, as if the actual contents of the included file had been written there. The file name is not quoted. Included files may be nested to a maximum depth of five. 13.2 $XREF - Generate Cross Reference $XREF generate a cross-reference listing at the end subprogram. 13.3 of each compiled $SEGMENT - Designate Segment Name $SEGMENT [identifier] the generated object-code of subsequent procedures is placed into the segment named by 'identifier'. If the $SEGMENT directive appears without any 'identifier' field, the generated object-code is placed in a segment whose name is ' , (eight spaces). FORTRAN Reference Manual Page 129 Chapter 13 FORTRAN Compile Time Options The SVS linker imposes a limit of 32K bytes of object code per segment. However, the linker will automatically split larger segments as required. Even for very large programs, a user normally should not have to explicitly partition his program into segments. 13.4 $COL72 - Restrict Source Lines to 72 Columns $COL72 indicates that source lines are to end in column 72. If this option is not specified, source lines can be up to 120 characters long. But, the ANSI FORTRAN-77 standard restriction of a maximum of 1360 characters per statement still applies. This corresponds to 20 lines of 66 columns. 13.5 FORTRAN-66 Compatibility Options The FORTRAN compiler accepts options which change features of the language in a manner compatible with FORTRAN-66. These options are listed in the following paragraphs. 13.5.1 $F66DO --Implement FORTRAN-66 DO Loops If the $F66DO option is used, DO loops always execute at once. 13.5.2 least $CHAREQU - Character and Numeric Data Equivalence' The $CHAREQU option means that CHARACTER and numeric data can now be assigned to the same COMMON areas. Using this option, CHARACTER and numeric data can also be EQUIVALENCE'd. In· addition, the $CHAREQU option indicates that non-CHARACTER variables can be initialized with CHARACTER data constants via the DATA statement. See Chapter 7 - "Data Initialization" for details. 13.5.3 $INT2 - Make Integers l6-Bits If the $INT2 option is used, the INTEGER data type is INTEGER.2 by default, although all the length specifications are still available if explicitly used in specification statements. If the $INT2 option is used, LOGICAL variables default to LOGICAL·l. Just as for INTEGER, all the length specifications for LOGICAL are still available if explicitly used in specification statements. Page 130 FORTRAN Reference Manual Chapter 13 FORTRAN Compile Time Options It should be noted that these last two features the ·storage unit· standards of FORTRAN-77, nevertheless. conflict with but are useful Rote: Although the $INT2 option changes the default size of INTEGER and LOGICAL variables, the FORTRAN system still expects to see 4-byte variables in those contexts where an INTEGER*4 (or a LOGICAL*4) is required. For example, the assigned GO TO statement still expects a 4-byte variable as the subject of the ASSIGN statement and any GO TO statement which references that variable. If the $INT2 option is set, actual parameter integer expressions (not variables or array elements but any constant or computed expression) are coerced to two byte values. Similarly, constant and computed logical expressions are coerced to one byte values if the $INT2 option is set. This makes expressions default to matching lengths with parameters of default length. A fairly common programming error is to compile a subprogram with $INT2 set but to call it from a compile in which $INT2 is not set. This leads to incompatible actual and formal arguments if all length specifications are defaulted by the FORTRAN system. FORTRAN Reference Manual Page 131 FORTRAN Compile Time Options Page 132 Chapter 13 FORTRAN Reference Manual Appendix A Messages from the FORTRAN System Appendix A - Messages from the FORTRAN System A.l o Compile-Time Error Messages 1 2 3 4 5 6 8 9 10 Unknown error Fatal error reading source block Non-numeric characters in label field Too many continuation lines Fatal end-of-file encountered Labeled continuation line Missing field on $ compiler directive line Unrecognizable $ compiler directive Input sourc~ file not a valid text file format Maximum depth of include file nesting exceeded 11 12 13 14 15 16 17 18 19 20 Integer constant overflow Error in real constant Too many digits in constant Identifier too long Character constant extends to end of line Character constant is zero length Illegal character in input Integer constant expected Label expected Error in label 21 Type name expected (INTEGER [*n) , REAL[*n], DOUBLE COMPLEX, LOGICAL [*n] , or CHARACTER[*n) INTEGER constant expected Extra characters at end of statement '(' expected Letter IMPLICIT'ed more than once 1)1 expected Letter expected Identifier expected Dimension(s) required in DIMENSION statement Array dimensioned more than once 22 23 24 25 26 27 28 29 30 31 32 33 Maximum of 7 dimensions in an array Incompatible arguments to EQUIVALENCE Variable appears more than once in statement FORTRAN Reference Manual a type PRECISION, specification Page 133 Appendix A Messages from the FORTRAN System 34 35 36 37 38 39 40 This identifier has already been declared This intrinsic function cannot be passed as an argument Identifier must be a variable Identifier must be a variable or the current FUNCTION name 'I' expected Named COMMON block already saved Variable already appears in a COMMON block 41 42 50 Variables in different COMMON blocks cannot be EQUIVALENCE'd Number of subscripts in EQUIVALENCE statement does not agree with variable declaration EQUIVALENCE subscript out of range Two distinct cells EQUIVALENCE'd to the same location in a COMMON block EQUIVALENCE statement extends a COMMON block in a negative direction EQUIVALENCE statement forces a variable to two distinct locations, not in a COMMON block Statement number expected Mixed CHARACTER and numeric items not allowed in same COMMON block CHARACTER items cannot be EQUIVALENCE'd to non-CHARACTER items Illegal symbols in an expression 51 52 53 54 55 56 57 58 59 60 Cannot use SUBROUTINE name in an expression Type of argument must be INTEGER or REAL Type of argument must be INTEGER, REAL or CHARACTER Types of comparisons must be compatible Type of expression must be LOGICAL Too many subscripts Too few subscripts Variable expected '.' expected Size of EQUIVALENCE'd CHARACTER items must be the same 61 62 63 64 65 70 Illegal assignment - types do not match Can only call SUBROUTINES Dummy arguments cannot appear in COMMON statements Dummy arguments cannot appear in EQUIVALENCE statements Assumed-size array declarations can only be used for dummy arrays Adjustable-size array declarations can only be used for dummy arrays Assumed-size array dimension specifier, "*", must be the upper bound of the last dimension Adjustable bound must be either a dummy argument or be in COMMON prior to appearance Adjustable bound must be simple integer expression containing only constants, COMMON variables, or PARAMETER constant names Cannot have more than one main program 71 The size of a named COMMON block must 43 44 45 46 47 48 49 66 67 68 69 Page 134 be the same in all FORTRAN Reference Manual Appendix A 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 93 94 95 96 98 99 Messages from the FORTRAN System subprograms Dummy arguments cannot appear in DATA statements Variables in blank COMMON cannot appear in DATA statements Names of SUBROUTINES, FUNCTIONS, INTRINSIC FUNCTIONS and such cannot appear in DATA statements Subscripts out of range in DATA statement Repeat count must be integer value greater than zero Constant expected Type conflict in DATA statement Number of variables does not match the number of values in DATA statement list Statement cannot have a label No such INTRINSIC function Type declaration for INTRINSIC function does not match actual type of INTRINSIC function Letter expected Type of FUNCTION does not agree with previous usage This subprogram has already appeared in this compilation This procedure has already been defined as appearing in another compilation unit via a $USES command Error in type of argument to INTRINSIC function SUBROUTINE/FUNCTION previously used as a FUNCTION/SUBROUTINE Unrecognizable statement Expression not allowed Missing END statement Fewer actual arguments than formal arguments in a FUNCTION or SUBROUTINE reference More actual arguments than formal arguments in a FUNCTION or SUBROUTINE reference Type of actual argument does not agree with formal argument The following procedures were called but not defined Size of type CHARACTER item must be between 1 and 255 INTEGER*4 variable required 100 Statement out of order 101 102 103 104 105 106 107 108 109 110 Unrecognizable statement Illegal jump into block Label already used for FORMAT Label already defined Jump to FORMAT label DO statement forbidden in this context DO label must follow a DO statement ENDIF forbidden in this context No matching IF for this ENDIF Improperly nested DO block in IF block III 112 113 114 ELSEIF forbidden in this context No matching IF for ELSEIF Improperly nested DO or ELSE block I (I expected FORTRAN Reference Manual Page 135 Messages from the FORTRAN System Appendix A 115 116 117 118 119 120 '). expected THEN expected Logical expression expected ELSE statement forbidden in this context No matching IF for ELSE Unconditional GOTO forbidden in this context 121 122 123 124 125 126 127 128 129 Assigned GOTO forbidden in this context Block IF statement forbidden in this context Logical IF statement forbidden in this context Arithmetic IF statement forbidden in this context I,' expected Expression of wrong type RETURN forbidden in this context STOP forbidden in this context END forbidden in this context 131 132 133 134 135 136 137 138 139 140 Label referenced but not defined DO or IF block not terminated FORMAT statement not permitted in this context FORMAT label already referenced FORMAT must be labeled Identifier expected Integer variable expected 'TO' expected Integer expression expected Assigned GOTO but no ASSIGN statements 141 142 143 144 145 146 147 148 Unrecognizable character constant as option Character constant expected as option Integer expression expected for unit designation STATUS option expected after ',' in CLOSE statement Character expression as filename in OPEN FILE= option must be present in OPEN statement RECL= option specified twice in OPEN statement Integer expression expected for RECL= option in OPEN statement Unrecognizable option in OPEN statement Direct access files must specify RECL= in OPEN statement 149 150 151 152 153 154 155 156 157 158 159 160 Assumed-sized arrays not allowed as input-output list elements End of statement encountered in implied DO, expressions beginning with' (' not allowed as input-output list elements Variable required as control for implied DO Expressions not allowed as reading input-output list elements REC= option appears twice in statement REC= options expects integer expression END- option only allowed in READ statement END- option appears twice in statement Unrecognizable input-output unit Unrecognizable format in input-output statement Page 136 FORTRAN Reference Manual Appendix A .161 162 163 164 165 166 167 169 170 171 Messages from the FORTRAN System Options expected after ',' in input-output statement Unrecognizable input-output list element Label used as format but not defined in FORMAT statement Integer variable used as assigned format but no ASSIGN statement Label of an executable statement used as format Integer variable expected for assigned format Label defined more than once as format FUNCTION references require "()" INTEGER expression expected for array dimension bound 172 Lower dimension bound must be less than or equal to upper dimension bound DATA statement cannot initialize arrays of unknown size 200 201 202 203 204 205 206 207 208 209 210 Variable name of named COMMON name expected This variable already SAVE'd Cannot SAVE dummy arguments Cannot SAVE COMMON variables INTEGER and LOGICAL *1, *2, or *4 only No *n allowed for DOUBLE PRECISION Only REAL*4 or REAL*8 allowed No *n allowed for COMPLEX Size expression only allowed for CHARACTER INTEGER constant expression expected INTEGER constant or INTEGER constant expression expected 211 212 213 214 215 216 217 218 219 220 CHARACTER substring expression out of range CHARACTER substring expression must be of type INTEGER Error in CHARACTER substring expression CHARACTER expression expected LOGICAL expression expected CHARACTER*(*} only allowed for dummy arguments Undeclared PARAMETER constant Constant expression not allowed Arithmetic operators only apply to numeric values Malformed COMPLEX constant 221 222 223 224 229 230 Maximum of seven levels of implied-DO allowed Error in DATA statement variable list Error in implied DO list in data statement Variables in named COMMON can only appear in a DATA statement which is in a BLOCK DATA subprogram Integer subscript expected Subscript error This identifier is already in use as an implied-DO control variable Integer constant expression or implied DO control variable expected Integer expression required Division by zero 231 Error in COMPLEX primary 225 226 227 228 FORTRAN Reference Manual Page 137 Messages from the FORTRAN System 232 233 234 235 236 237 238 239 240 241 242 2t3 244 245 246 247 248 249 250 251 252 253 254 255 256 270 271 272 273 274 275 276 277 278 279 Appendix A Numeric expression or CHARACTER expression expected COMPLEX can only compare for equality COMPLEX is not compatible with DOUBLE PRECISION Constant expression expected ENTRY statements must appear in SUBROUTINE or FUNCTION subprograms ENTRY statements cannot be within a block IF or a 00 statement range Concatenation only applies to CHARACTER values 'I' expected Substring operations only apply to CHARACTER variables or CHARACTER array elements Error in implied 00 expression in a DATA statement Implied DO iteration count is zero in a DATA statement Error in formal argument list Alternate return is not allowed in a FUNCTION subprogram Substring error in EQUIVALENCE statement EQUIVALENCE statement must not require *2, *4, or *8 variables to be allocated on odd byte addresses EQUIVALENCE statement must not require a COMMON block to be allocated on odd byte addresses CHARACTER arguments cannot contain concatenation of values that are of size *(*) Numeric expression expected SUBROUTINE or FUNCTION name has already been used as a COMMON name Recursive calls are not allowed Statement-FUNCTIONS require variable or value arguments Alternate ENTRY in CHARACTER FUNCTION must be of type CHARACTER and must be the same size as the FUNCTION This INTRINSIC FUNCTION cannot be passed as an argument Executable statements cannot appear in BLOCK DATA subprograms An argument to an ENTRY statement has already appeared as a local variable 280 Assigned GO TO variable must be INTEGER or INTEGER*4 INTEGER, REAL, or DOUBLE PRECISION variable expected INTEGER, REAL, or DOUBLE PRECISION expression expected Unrecognizable element in option list Option appears more than once in an option list Incorrect type for variable Variable must be *4 in size CHARACTER variable or CHARACTER array element required CHARACTER expression expected Cannot have FILE and UNIT specifier in same INQUIRE statement Must have a FILE or UNIT specifier in INQUIRE statement 281 282 Must have UNIT specifier PRINT statement requires no option list - use WRITE Page 138 FORTRAN Reference Manual Appendix A Messages from the FORTRAN System 283 284 285 286 287 288 289 290 WRITE statement must have an option list READ statement must not have both RECz and END= options Must not specify REC= option with * format specifier Cannot do internal input-output with * format specifier Cannot use REC- specifier with internal input-output Malformed implied DO loop Implied DO loop must have simple variable for loop control Wrong number of arguments to intrinsic function 291 292 293 294 295 296 297 350 Unit set more than once in input-output statement No unit specified in input-output statement Error in FORMAT statement Hexadecimal constant expected Too many characters in statement Can't find $INCLUDE file Sub arrays cannot exceed 32766 bytes in size Procedure too large 400 401 402 403 407 408 409 Code file write error Error in rereading code file Error in reopening text file Procedure too large (code buffer too small) Not enough room for intermediate code file Error in writing code file Error in reading intermediate code file A.2 Run-Time Error Messages These messages are issued by the input-output run time system, and represent the possible values of 'iostat' in an 'iolist'. -1 End of file found on a READ with no END= option. 600 601 602 603 604 605 606 607 608 609 610 FORMAT statement missing final ')' Sign not expected in input Sign not followed by digit in input Digit expected in input Missing N or Z after B in format Unexpected character in format Zero repetition factor in format not allowed Integer expected for w field in format Positive integer required for w field in format '.' expected in format Integer expected for d field in format 611 612 613 614 615 616 617 Integer expected for e field in format Positive integer required for e field in format Positive integer required for w field in A format Hollerith field in format must not appear for reading Hollerith field in format requires repetition factor X field in format requires repetition factor P field in format requires repetition factor FORTRAN Reference Manual Page 139 Messages from the FORTRAN System Appendix A 618 619 620 Integer appears before '+' or '-' in format Integer expected after '+' or '-' in format P format expected after signed repetition factor in format 621 622 623 624 625 626 627 628 Maximum nesting level (10 levels) for formats exceeded ')' has repetition factor in format Integer followed by',' illegal in format '0' is illegal format control character Character constant must not appear in format for reading Character constant in format must not be repeated 'I' in format must not be repeated 'I, '$', I:', IS', eSP' and ISS' in format must not be repeated 8M or BZ format control must not be repeated Attempt to perform input-output on unknown unit number 629 630 631 632 633 634 635 636 637 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 Formatted or list-directed input-output attempted opened as unformatted Format fails to begin with '(I I format expected for integer read P, 0, G or B format expected for real read Two '.' characters in formatted real read Digit expected in formatted real read L format expected for logical read T or F expected in logical read A format expected for character read on file I format expected for integer write v field in P format not greater than d field + 1 Scale factor out of range'of d field in E format E, 0, G or P format expected for real write L format expected for logical write A format expected for character write Attempt to do unformatted input-output to a file opened as formatted Unable to write blocked output - possibly no room on output device Unable to read blocked input Error in formatted text file - no carriage-return in last 512 bytes Integer overflow on input T, TL or TR in format must not be repeated positive integer expected for c field in T, TL or TR format Attempt to open direct-access unit on unblocked device Attempt to do external input-output on a unit beyond endof-file record Attempt to position a unit for direct-access on a nonpositive record number Attempt to do direct-access on a unit opened as sequential Attempt to position direct-access unit on an unblocked device Attempt to position direct-access unit beyond end-of-file Page 140 FORTRAN Reference Manual Appendix A 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 697 698 699 Messages from the FORTRAN System for reading Attempt to backspace unit connected to unblocked unformatted file device or Attempt to backspace sequential, unformatted unit Argument to ASIN or ACOS out of bounds - ABS(x) > 1.0 Argument to SIN or COS too large - ABS(x) > 10@+(6) Attempt to do unformatted input-output to internal unit Attempt to put more than one record into an internal unit Attempt to write more characters to an internal unit than its length EOF called on unknown unit Direct-access formatted input files must not use DLE blank compression Error in opening file Error in closing file Can't specify KEEP in close if file opened SCRATCH Unrecognizable option specified as character value input-output statement File name required unless status is SCRATCH Must not name file if status is SCRATCH Record length not allowed for sequential files Record length must be positive Record length must be specified for direct-access files BLANK option only for formatted files Rewind only allowed on sequential files Endfile only allowed on sequential files in Backspace only allowed on sequential files Formatted records must be less than or equal to 512 characters More characters written to internal file record than record length Incorrect number of characters read in formatted record of direct-access file Attempt to write too many characters into formatted record of direct-access file No repeatable edit descriptor found and format exhausted Digit expected in input field exponent Too many digits in input real number Numeric field expected in input Unexpected character encountered in list-directed input Repeat factor in list-directed input must be positive ',' between reals for complex expected in list-directed input ')' expected to terminate complex in list-directed input Attempt to do list-directed input-output to direct-access file Integer variable not currently assigned a FORMAT label End-of-file encountered on a read with no END= option Integer variable not assigned a label used in assigned GOTO FORTRAN Reference Manual Page 141 Messages from the FORTRAN System Appendix A statement 701 702 703 704 705 706 707 708 Integer input item expected for list-directed input Numeric input item expected for list-directed input Logical input item expected for list-directed input Complex input item expected for list-directed input Character input item expected for list-directed input Incorrect number of bytes read or written to direct-access unformatted file Substring index range error Unable to perform FCHAIN 1000+ Compiler debug error messages - should never appear in correct programs. These normally are an indication that the wrong file was specified as the input to the code generator. Page 142 FORTRAN Reference Manual Appendix B Intrinsic Functions Appendix B - Intrinsic Functions +------------+------------+---------+----------+----------------------+ Intrinsic Number of Generic Specific Type of I Function I Arguments I Name I Name I Argument I Function I ~~~:~:~ Integer I +------------+------------+---------+----------+----------+-----------+ ~~n~~~:!~~ I 1 I INT I I ~:ix IDINT I :::i Double I +------------+------------+---------+----------+----------+-----------+ ~~n~:~~ion 1 REAL ~~iT ~~~:~:~ :::i . SNGL Double Real +------------+------------+---------+----------+----------+-----------+ Integer Double I I I I I I I Conversion to Double DBLE 1 Real Double Complex Double Double Double Real Double Complex Complex Complex Complex +------------+------------+---------+----------+----------+-----------+ Integer Complex Conversion to Complex 1 or 2 CMPLX +------------+------------+---------+----------+----------+-----------+ Conversion I l ' 'ICHAR I Character \ Integer I I I +------------+------------+---------+----------+----------+-----------+ I I I I I I I+------------+------------+---------+----------+----------+-----------+ to Integer +------------+------------+---------+----------+----------+-----------+ Conversion I 1 I I CHAR I Integer I Character I to Character Truncation I Nearest Whole AINT 1 I 1 I ANINT AINT DINT I ANINT DNINT Real Double I Real Double Real Double I Real Double I +------------+------------+---------+----------+----------+-----------+ FORTRAN Reference Manual Page 143 Appendix B Intrinsic Functions +------------+------------+---------+----------+---------------------+ Intrinsic I Number of I Generic I Specific I Type of I I I I +------------+------------+---------+----------+----------+----------+ Function Arguments Name Name Argument Function IDNINT Double Integer lABS ABS DABS CABS Integer Real Double Complex Integer Real Double Real +------------+------------+---------+----------+----------+----------+ Nearest I 1 I NINT I NINT I Real I Integer I Integer Absolute Value ABS 1 +------------+------------+---------+----------+----------+----------+ ~:~~~;2 MOD ~gD ~~!~ger ~~!~ger DMOD Double Double +------------+------------+---------+----------+----------+----------+ I I I I I I I ~~a~~!~r I 2 I SIGN I ~~~~N I DSIGN I ~~!~ger I Double ~~!~ger I Double +------------+------------+---------+----------+----------+----------+ Positive Difference I 2 I DIM I I 101M DIM DDIM I Integer Real Double I Integer Real Double I +------------+------------+--------~+----------+----------+----------+ I:~~m~on I 2 I I DPROD I Real I Double I +------------+------------+---------+----------+----------+----------+ Choosing Largest Value 2 or more MAX I ~~l I i~!~ger I i~!~ger I +----------+----------+----------+ I I I DMAXl , AMAXO MAXl Double Double Integer Real Real Integer +------------+------------+---------+----------+----------+----------+ Choosing Smallest Value 2 or more MIN I MINO AMINl DMINl I Real Integer I Integer I Real Double Double +----------+----------+----------+ I I I I +------------+------------+---------+----------+----------+----------+ I I I I I I I +------------+------------+---------+----------+----------+----------+ I I I I I Length 1 Index of Substring 2 AMINO MINl Integer Real Real Integer LEN Character Integer 'INDEX Character \ Integer . +------------+------------+---------+----------+----------+----------+ Page 144 FORTRAN Reference Manual Appendix B Intrinsic Functions +------------+------------+---------+----------+---------------------+ Intrinsic I Number of 'GeneriC' Specific I Type of I I I+------------+------------+---------+----------+----------+----------+ Function Arguments Imaginary Part of Complex Argument Name Name AIMAG Argument Function Complex Real 1 +------------+------------+---------+----------+----------+----------+ Com~lex I l' I CONJG I Complex I Complex I I ConJugate +------------+------------+---------+----------+----------+----------+ :~~~re 1 SORT ~~~iT ~~~~le ~~~~le CSORT Complex Complex +------------+------------+---------+----------+----------+----------+ ~~~~nen1 EXP I ~~~p I ~~~~le I .~~~~le CEXP Complex Complex I +------------+------------+---------+----------+----------+----------+ I I I I I I I I I I ~~~~~~~hm I 1 I 1 I I LOG I LOG10 I I ~g~ CLOG I I ~~~~le Complex I I ~~~~le Complex I I +------------+------------+--~------+----------+----------+----------+ I Common Logarithm ALOG10 DLOG10 Real Double. Real Double +------------+------------+---------+----------+----------+--~-------+ Sine I 1 I SIN I I'~~~N CSIN I ~~~~le Complex I ~~~~le Complex I +I-::::::-----+I-----:------+I-:::-----+I-~~:-----+I-~~:~::---+I-~~:~::---+I CCOS Complex Complex +------------+------------+---------+----------+----------+----------+ Tangent I 1 I TAN I TAN I Real I Real I I I +------------+------------+---------+----------+----------+----------+ I I I I I I DTAN Double Double DASIN Double Double +------------+------------+---------+----------+----------+----------+ Arcsine I 1 I ASIN I ASIN I Real I Real I Arccosine 1 ACOS Real Real .\ DACOS Double Double +---------~--+------------+---------+----------+----------+----------+ FORTRAN Reference Manual ACOS Page 145 Appendix B Intrinsic Functions +------------+------------+---------+----------+---------------------+ Intrinsic, Number of I Generic , Specific \ Type of I I I+------------+------------+---------+----------+----------+----------+ I I I I I I+------------+---------+----------+----------+----------+ I I I I +------------+------------+---------+----------+----------+----------+ I I I I I I I+------------+------------+---------+----------+----------+----------+ I I I I I I I+----------~-+------------+---------+----------+----------+----------+ I I I I I I I Function Arguments Name 1 ATAN Argument Function ATAN DATAN Real Double Real Double 2 ATAN2 'ATAN2 DATAN2 Real Double , Real Double Hyperbolic Sine 1 SINH SINH DSINH Real Double Real Double Hyperbolic Cosine 1 COSH COSH DCOSH Real Double Real Double Hyperbolic Tangent 1 TANH TANH DTANH Real Double Real Double Arctangent Name j-~~:~~~~~;--j-----:------j---------j-:::------j-:::::::::j-:::::::--j +------------+------------+---------+----------+----------+----------+ ,~~:~~:;lY I 2' , LGT I Character' Logical , +------------+------------+---------+----------+----------+----------+ ,~~~::~~~~, 2 ., , LLE , Character' Logical , +------------+------------+---------+----------+----------+----------+ LeXiCallY, 2 I , LLT I Character I Logical I Less Than +------------+------------+---------+----------+----------+----------+ B.l ' Notes on the Intrinsic Functions The INT function truncates real or double precision arguments towards zero. If the argument to INT is a complex number, the function is applied to the real part of the complex argument. IFIX is the same as INT for real arguments. If the REAL or DBLE functions are applied to a complex ment, the result is the real part of the argument. argu- CMPLX can have one or two arguments. If there is one argument, it can be of type integer, real, double precision or complex. If the argument is of type integer, real or double precision, the result is a complex value whose real part is that of the argument, and whose imaginary part is zero. Page 146 FORTRAN Reference Manu~l Appendix B Intrinsic Functions If CMPLX has two arguments, they must both be of the same type. The arguments can be of type integer, real or double precision. The result is a complex value whose real part is the first argument and whose imaginary part is the second argument. ICHAR converts from character to integer. The first character in the collating sequence is position a and the last character in the sequence is 'n'-l, where 'n' is the number of, characters in the character set. In the trigonometric functions, all angles are in radians. Functions of complex arguments yield principal value of the function. a result which is the The INDEX function returns the index where its second argument starts in its first argument. If the first argument does not contain the second argument, or if the second argument is longer than the first argument, the INDEX function returns a value of zero. All arguments in an intrinsic function reference must be of the same type. B.2 Restrictions on Ranges of Arguments When intrinsic functions are referenced by their specific names, the restrictions on ranges of arguments and results are as follows: Remaindering MOD, AMOD and DMOD are second argument is zero. undefined when their Transference of Sign If the first argument to ISIGN, SIGN or DSIGN zero, the result is zero. is Square Root SQRT and DSQRT require an argument which is not less than zero. CSQRT returns a value which is the principal value and is greater than or equal to zero. If the real part of the result is zero, the imaginary part is greater than or equal to zero. Logarithms ALOG, DLOG, ALOG10 and DLOG10 require an argument greater than zero. The argument to CLOG must not be (0.0, 0.0). If the real part of the ~rgument is less than zero and the imaginary part 1S zero, the imaginary part of the result is 'pi', otherwise the imaginary part of the result lines in the range: FORTRAN Reference Manual Page 147 Appendix B Intrinsic Functions -pi < imaginary part <= pi Arcsine and Arccosine ASIN, DASIN, ACOS and DCOS requir~ that the absolute value of their argument be not greater than one. The result of arcsine lies in the range -pi/2 <= result <= pi/2 and the result. of arccosine lies in o B.3 <= the range result <= pi Non Standard Intrinsic Functions and Subroutines The functions and subroutines described here are non-standard SVS FORTRAN-77 extensions to the FORTRAN-77 language. B.3.l POKE - Store Into Arbitrary Memory Location The POKE subroutine stores a byte into location. The interface definition is: an arbitrary memory SUBROUTINE POKE(IADDR, IVAL) INTEGER IADDR, IVAL*l The POKE subroutine sets the memory location addressed by IADDR to the ~yti value of the variable IVAL. IVAL must be a variable that is ec ared INTEGER*l in the calling procedure or POKE will not work as expected. B.3.2 IPEEK - Read From Arbitrary Memory Location The IPEEK function gets a byte from an arbitrary tion. The interface definition is: memory loca- INTEGER*4 FUNCTION IPEEK(IADDR) INTEGER IADDR IADDR is the address of a memory location. The IPEEK function returns the signed value of the byte stored at that location. B.3.3 VERS - Print Date and Version The VERS subroutine prints the date and version of the FORTRAN-11 run-time system. The interface definition is: SUBROUTINE Page 148 SVS VERS FORTRAN Reference Manual Intrinsic Functions Appendix B There are no arguments to the VERS subroutine. B.3.4 RAN - Random Number Generator The function RAN generates· pseudo random numbers in the val [0.0,1.0). The definition is: inter- REAL FUNCTION RAN(I) INTEGER*4 I If the value of the parameter 'I' is zero, then a new random result is returned. If 'I' is greater than zero, a new sequence of random numbers is stated, and the first value in that sequence is returned. If 'I' is negative, the same number that was returned for the last call to RAN is returned. B.3.5 IARGC - Number of Arguments The function IARGC returns the number of command line arguments passed to the program. Its declaration is: INTEGER*4 FUNCTION IARGC() INTEGER*4 FUNCTION IARGC() The exact meaning of the value returned depends operating syst~m under which the program is running. B.3.6 upon the GETARG - Access an Argument The subroutine GETARG is used to fetch line arguments. The form is: the value of command SUBROUTINE GETARG(I,C) INTEGER*41 CHARACTER*(*)C The value of the I'th command line argument is returned in the variable C. If there is no argument corresponding to 'I', then C is set to blanks. If the length of the argument is greater than the length of C, then only that part tpat fits is returned, and if it is smaller, than the rest of C is filled with blanks. FORTRAN Reference Manual Page 149 Intrinsic Functions Page 150 Appendix B FORTRAN Reference Manual Appendix C Data Representations Appendix C - Data Representations This appendix describes the ways that SVS FORTRAN represents data in storage and the mechanisms for passing arguments to subroutines and functions. This appendix is intended as a guide to those programmers who wish to write modules in languages other than FORTRAN and have those modules interface to FORTRAN. C.l Storage Allocation This section describes the way in which storage is allocated to variables of various types. In general, any word value (a value which occupies 16 bits) is always aligned on-a-word boundary. Anything larger than a word is also aligned on a word boundary. Values that can fit into a single byte are aligned on a byte boundary. INTEGER, REAL and LOGICAL data types all occupy the same amount of storage,namely 32 bits (four bytes or two words). DOUBLE PRECISION occupies 64 bits (eight bytes or four words). COMPLEX is represented as a pair of single precision real data values and so occupies 64 bits (eight bytes or four words). There are provisions for indicating that integer and logical data types occupy less storage. INTEGER*l occupies a bits (one byte), boundary. INTEGER*2 occupies 16 bits (two bytes or one word), aligned on a word boundary. aligned on a byte INTEGER and INTEGER*4 occupy 32 bits (four bytes or two words), aligned on a word boundary. REAL and REAL*4 occupy 32 bits (four bytes or two words), aligned on a word boundary. A REAL element has a sign bit, an a-bit exponent and a 23-bit mantissa. SVS FORTRAN Reference Manual Page 151 Data Representations Appendix C FORTRAN REAL elements conform to the IEEE standard for reals as defined in the March 1981 Computer magazine. The layout of a REAL element is shown below. DOUBLE PRECISION and REAL*8 elements occupy 64 bits (eight bytes or four words), aligned on a word boundary. A DOUBLE PRECISION element has a sign bit, an ll-bit exponent and a 52-bit mantissa. SVS FORTRAN DOUBLE PRECISION elements conform to the IEEE standard for double precision data as defined in the March 1981 Computer magazine. The layout of a DOUBLE PRECISION element is shown below. COMPLEX elements are represented by two REAL elements. The first element represents the real part of the number, the second represents the imaginary part. LOGICAL*l occupies one byte (8 bits) of storage, aligned on a byte boundary. A value of 0 represents the value .FALSB. • A value of 1 represents the value .TRUB. • Any other value is an "undefined" logical value. LOGICAL*2 occupies two bytes (16 bits) of storage, aligned on a word boundary. A value of 0 represents the value .FALSB.. A value of 1 represents the value .TRUB. • Any other value is an "undefined" logical value. LOGICAL and LOGICAL*4 occupies four bytes (32 bits) of storage, aligned on a word boundary. A value of 0 represents the value .FALSB. • A value of 1 represents the value .TRUE. • Any other value is an "undefined" logical value. C.2 Data Representations Whatever the size of the data element in question, the most significant bit of the data element is always in the lowest numbered byte of however many bytes are required to represent that object. The diagrams below should clarify this. Page 152 FORTRAN Reference Manual Appendix C C.2.1 Data Representations Representation of Integers bit --> 7 0 INTEGER*l +--------+ I byte 0 I +--------+ INTEGER*2 +--------+--------+ I byte 0 I byte 1 I +--------+--------+ INTEGER*4 +--------+--------+--------+--------+ I byte 0 I byte 1 I byte 2 I byte 3 I +--------+--------+--------+--------+ o 15 o 31 C.2.2 Representation of REAL and DOUBLE PRECISION REAL and DOUBLE PRECISION data elements are represented according to the proposed IEEE standard described in Computer magazine of March, 1981. The diagrams below illustrates the representation. 31 30 o 23 22 +---+----------------+----------------------------------------+ I S I Exponen~ I Mantissa I +---+----------------+----------------------------------------+ I I Exponent, biased by 127 M!ntissa (23 + 1 bits) Sign ~ 62 63 Representation 52 51 o +---+----------------+----------------------------------------+ I S I Exponent I Mantissa I +---+----------------+----------------------------------------+ I M~ntissa (52 + 1 bits) I Exponent, biased by 1023 Sign FORTRAN Reference Manual Page 153 Appendix C Data Representations DOUBLE PRECISION Representation The parts of REAL and DOUBLE PRECISION numbers are as follows: a one-bit sign bit designated by "S" in the diagrams above. The sign bit is a 1 if, and only if, the number is negative. a biased exponent. The exponent is eight bits for a REAL number, and is eleven bits for a DOUBLE PRECISION number. The values of all zeros, and all ones, are reserved values for exponents. a normalized mantissa, with the high-order 1 bit "hidden". The mantissa is 23 bits for a REAL number, and is 52 bits for a DOUBLE PRECISION number. A REAL or DOUBLE PRECISION number is represented by the form: 2ex ponent-bias * l.f where If' is the bits in the mantissa. C.2.3 Representation of Extreme Numbers zero (signed) is represented by an mantissa of zero. exponent of zero, and a denormalized numbers are a product of "gradual underflow". They non-zero numbers with an exponent of zero. form of a denormalized number is: are The 2exponent-bias+l * O.f where If' is the bits in the mantissa. signed infinity (that is, affine infinity) is represented by the largest value that the exponent can assume (all ones), and a zero mantissa. When infinity is printed by a FORTRAN program, it appears as either plus '+++.+++' or minus signs '---.---' depending on the sign. Not-a-Number (NaN) is represented exponent can mantissa. The ted printing question marks Page 154 by the largest value that the assume (all ones), and a non-zero sign is usually ignored. Formatof NaN appears as a sequence of '111.111'. FORTRAN Reference Manual Appendix C Data Representations Normalized REAL and DOUBLE PRECISION numbers are said to contain a "hidden" bit, providing for one more bit of precision than would normally be the case. C.2.4 Hexadecimal Representation of Selected Numbers +-----------+----------+------------------+ I Value I REAL I PRECISION I +-----------+----------+------------------+ +0 00000000 0000000000000000 -0 80000000 8000000000000000 +1.0 -1.0 3F800000 BF800000 3FFOOOOOOOOOOOOO BFFOOOOOOOOOOOOO +2.0 +3.0 40000000 40400000 4000000000000000 4008000000000000 +Infinity -Infinity 7F800000 FF800000 7FFOOOOOOOOOOOOO FFFOOOOOOOOOOOOO NaN 7F8xxxxx 7FFxxxxxxxxxxxxx +-----------+----------+------------------+ C.2.S Deviations from the Proposed IEEE Standard Deviations from the proposed IEEE standard in this tion are as follows: implementa- affine mapping for infinities, normalizing mode for denormalized numbers, rounds approximately to nearest - 7 or computed, but the "sticky" bit is not, more guard bits are exception flags are not implemented, conversion between binary and decimal is not implemented. C.2.6 Arithmetic Operations on Extreme Values This subsection describes the results derived from applying the basic arithmetic operations on combinations of extreme values and ordinary values. No traps or any other exception actions are taken. All inputs are assumed to be positive. Overflow, and cancellation are assumed not to happen. FORTRAN Reference Manual underflow, Page 155 Data Representations Appendix C In all the tables below, the abbreviations have meanings: the following +--------------+---------------------------------+ I Abbreviation I Meaning I +--------------+---------------------------------+ Den Denormalized Number Num Inf NaN Uno Normalized Number Infinity (positive or negative) Not a Number Unordered +--------------+---------------------------------+ +---------------------------------------------------+ I Addition and Subtraction I +-----------+---------------------------------------+ Left I Right Operand I Operand 0 I Den I Num I Inf I NaN +-------+-------+-------+-------+-------+ o I 0 I Den I Num I Inf I NaN I +-----------+-------+-------+-------+-------+-------+ I Den I Den I Den I Num I Inf I NaN I +-----------+-------+-------+-------+-------+-----~-+ I Num I Num I Num I Num I Inf I NaN I +-----------+-------+-------+-------+-------+-------+ I Inf I Inf I Inf I Inf I Note 11 NaN I +-----------+-------+-------+-------+-------+-------+ I NaN I NaN I NaN I NaN I NaN I NaN I +-----------+-------+-------+-------+-------+-------+ Note 1: Inf + Inf = Inf; Inf - Inf = NaN +---------------------------------------------------+ I Multiplication I +-----------+---------------------------------------+ Left \ Right Operand I Operand o 0 I Den I Num I Inf I NaN +-------+-------+-------+-------+-------+ 0 0 0 NaN NaN I I I I I I +-~---------+-------+-------+-------+-------+-------+ I Den I 0 I 0 I Num I Inf I NaN I +-----------+-------+-------+-------+-------+-------+ Num 0 Num Num Inf NaN +-----------+-------+-------+-------+-------+-------+ Inf NaN Inf Inf Inf NaN +-----------+-------+-------+-------+-------+-------+ NaN NaN NaN NaN NaN NaN +-----------+-------+-------+-------+-------+-------+ I I I I I I I I I I I I I I I I I I I I I Page 156 FORTRAN Reference Manual Data Representations Appendix C +---------------------------------------------------+ I Division I +-----------+---------------------------------------+ Left, Right Operand I Operand 0 I Den I Num I lnf I NaN +-------+-------+-------+-------+-------+ o NaN 0 0 0 NaN +-----------+-------+-------+-------+-------+-------+ I Den I lnf I Num I Num I 0 I NaN I +-----------+-------+-------+-------+-------+-------+ Num lnf Num Num 0 NaN +-----------+-------+-------+-------+-------+-------+ lnf Inf lnf lnf NaN NaN +-----------+-------+-------+-------+-------+-------+ NaN NaN NaN NaN NaN NaN +-----------+-------+-------+-------+-------+-------+ I I I I I I I I I I I I I I I I I I I I I I I I I I I +---------------------------------------------------+ I Comparison I +-----------+---------------------------------------+ Left, Right Operand I Operand 0 I Den I Num I lnf I NaN +-------+-------+-------+-------+-------+ o = < < < Uno +-----------+-------+-------+-------+-------+-------+ Den > < < Uno +-----------+-------+-------+-------+-------+-------+ Num > > < Uno +-----------+-------+-------+-------+-------+-------+ I lnf I > I > I > I I Uno I +-----------T-------+-------+-------+-------+-------+ I NaN I Uno I Uno I Uno I Uno I Uno I +-----------+-------+-------+-------+-------+-------+ I I I I I I I I I I I I I I I I I I I I Notes: NaN compared with NaN is Unordered, and also results in inequality. +0 compares equal to -0. FORTRAN Reference Manual Page 157 Appendix C Data Representations +---------------------------------------------------+ I Max I +-----------+---------------------------------------+ Left \ Right Operand I Operand 0 I Den I Num I lnf NaN +-------+-------+-------+-------+-------+ 0 Den Num lnf NaN +-----------+-------+-------+-------+-------+-------+ Den Den Den Num lnf NaN +-----------+-------+-------+-------+-------+-------+ Num Num Num Num lnf NaN +-----------+-------+-------+-------+-------+-------+ I lnf I lnf I lnf I lnf I lnf I NaN I +-----------+-------+-------+-------+-------+-------+ NaN NaN NaN NaN NaN NaN +-----------+-------+-------+-------+-------+-------+ o I I I I I I I I I I I I I I I I I I I I I I I I I I I +---------------------------------------------------+ I Min I +-----------+---------------------------------------+ Left I Right Operand I Operand 0 I Den I Num I lnf I NaN +-------+-------+-------+-------+-------+ o 0 0 0 0 NaN +-----------+-------+-------+-------+-------+-------+ I Den I 0 I Den I Den I Den I NaN I +-----------+-------+-------+-------+-------+-------+ I Num I 0 I Den I Num I Num I NaN I +-----------+-------+-------+-------+-------+-------+ lnf 0 Den Num lnf NaN +-----------+-------+-------+-------+-------+-------+ NaN NaN NaN NaN NaN NaN +-----------+-------+-------+-------+-------+-------+ I I I I I I I I I I I I I I I I I I I I Page 158 FORTRAN Reference Manual Appendix C C.2.7 Data Representations Representation of Logicals bit --> 7 o +--------+ LOGICAL*1 I byte 0 I +--------+ 15 LOGICAL*2 LOGICAL*4 C.2.B o +--------+--------+ I byte 0 I byte 1 I +--------+--------+ o 31 +--------+--------+--------+--------+ I byte 0 I byte 1 I byte 2 I byte 3 I +--------+--------+--------+--------+ Storage of Arrays Arrays are stored with their elements in a specific storage order. The elements are actually stored in a linear sequence of storage elements. FORTRAN arrays are stored in column major order, such that first subscript in a multi-dimensional array varies fastest. position of an arbitrary element in an array is: the The l+SUM( (Si-Li*PRODUCT(Uj-L j » where 'SkI is the value of the subscript expression specified for dimension bound of dimension eke. The subscript 'j' in the product above varies between land 'i'-l for any given dimension. C.3 Argument Passing Mechanism This section describes the way in which arguments are passed in SVS FORTRAN. All arguments to FORTRAN subroutines and functions are passed by reference. For every argument except a CHARACTER object, a 32-bit pointer to the object is pushed onto the stack. When CHARACTER objects are passed in FORTRAN-77, a 32-bit pointer to the CHARACTER object is pushed onto the stack, followed by a l6-bit value which is the length of the CHARACTER object. Pointers to actual arguments are pushed onto the stack in the order in which they are declared in a subroutine or function FORTRAN Reference Manual Page 159 Appendix C Data Representations declaration. Actual arguments which are expressions are evaluated before the subroutine or function call. The result of the expression is assigned to a temporary storage area and a pointer to the temporary is pushed onto the stack. Normally 4 bytes are utilized for the temporary created to store a numeric expression (8 bytes for double precision). The number of bytes utilized will be different if the $INT2 option is set. In this case, integer expressions (including constants) are placed into 2 byte temporaries and logical expressions (including constants) are placed into 1 byte temporaries. In the exit code of a procedure, all arguments from the stack before the routine returns. C.4 are discarded Function Results Functions return their values in register DO (or 00/01 for double precision and complex return values). C.S Register Conventions Registers AO, Al, DO, 01, and 02 are available· as scratch registers in called routines. That is, they may be clobbered by functions and subroutines. All other registers must be preserved across calls. In addition, register A4 and AS must contain their original values whenever any external routine is called. A4 is used in addressing external entry points and AS is used to access the standard input and output, command line arguments, etc. Page 160 FORTRAN Reference Manual Appendix D ASCII Character Set Table Appendix D - ASCII Character Set Table +-------------+-------------+-------------+--------------+ I hex char I hex char ~ hex char I hex char I +-------------+-------------+-------------+--------------+ 00 NUL 20 SP 40 @ 60 01 02 03 04 05 06 07 08 09 OA OB OC OD OE OF SOH STX ETX EOT ENQ ACK BEL BS HT LF VT FF CR SO S~ 21 I 22" 23. 24 $ 25' 26 & 27' 28 ( 29) 2A * 2B + 2C 20 2E. 2F / 41 42 43 44 45 46 47 48 49 4A 4B 4C 40 4E 4F 11 12 13 14 15 16 17 18 19 A B C D E DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS GS RS US 31 1 32 2 33 3 34 4 35 5 36 6 37 7 38 8 39 9 3A 3B 3C < 3D:I: 3E > 3F? 51 0 52 R 53 S 54 T 55 U 56 V 57 W 58 X 59 Y SA Z 5B [ 5C \ 50) 5E" SF F G H I J K L M N 0 61 62 63 64 65 66 67 68 69 6A 6B 6C 60 6E 6F a b c d e f 9 h i j k 1 m n 0 +-------------+-------------+-------------+--------------+ 10 DLE 30 0 50 P 70 P LA 1B 1C 1D IE 1F 71 72 73 74 75 76 77 78 79 7A 7B 7C 70 7E 7F q r s t u v w x Y z 1 DEL +-------------+-------------+---------=---+--------------+ FORTRAN Reference Manual Page 161 ASCII Character Set Table Page 162 Appendix 0 FORTRAN Reference Manual Appendix E Operating the SVS FORTRAN System Appendix B - Operating the SVS PORTRAN Systea This appendix will describe those characteristics of the SVS PORTRAN system which are similar among the various environments in which the system operates. The appendix which follows this one describes the implementation specific details of the PORTRAN system under your operating system. The information in this appendix describes the PORTRAN system in the form it is released by SVS. Some of the vendors of the system provide additional utilities which can used in conjunction with SVS PORTRAN and which may alter the appearance of the system. E.I System Components In order to most effectively utilize the SVS PORTRAN system, it is necessary to understand the function and operation of its various components. In all environments a completely straight forward procedure is provided for compiling and executing simple FORTRAN programs (see next appendix). The information provided here, will only be necessary for more complicated situations involving separate compilation and multiple source languages. E.l.l Compiler Front End FORTRAN source programs (actually PORTRAN compilation units consisting of one or more procedures with or without a main program and/or a block data subprogram) are accepted by the compiler front end, syntax checked, and an intermediate representation of the program (compilation unit) is written to a file. This file is passed to the code generator which generates object code. The input source program may Rinclude" other files (see Chapter 13). In addition to the input source file, the FORTRAN compiler front end accepts certain directives from the command line, which are described in the ·Command Line Directives and Compiler Options R section of this appendix. Input files to the PORTRAN front end generally are files with names which end in ·.for R, although this differs among operating environments. The output file from the FORTRAN compiler front end is an intermediate representation of the program which is placed in a file which generally ends in R.i". There is FORTRAN Reference Manual Page 163 operating the SVS FORTRAN ,System Appendix E virtually nothing which can be done with this ".i" file except provide it as input to the code generator. E.l.2 Code Generator The code generator for the FORTRAN system accepts as input the ".i" file produced by the front end and generates linkable object code in a file with a name which generally ends in ".obj". The same code generator is utilized in compiling SVS Pascal, FORTRAN, and SVS C and the resulting ".obj" files are linkable providing the applicable rules are followed. SVS E.l.3 Linker A utility is provided with SVS FORTRAN for linking ".obj" files with each other and with run time libraries which are part of the language system. The linker is highly specific to the operating environment and its operation is described in detail in the following appendix. There is, however, certain general information which applies to all of the linkers. Each linker accepts as inputs ".obj" files and produces an output which is acceptable to the operating system as an object file. In some operating environments, the linker's output file is further linkable in the target environment with object code generated by the operating system assembler, etc. In all cases, the linker may be run only once per executable image. The input to the linker must contain exactly one main program but may contain many object files derived from separate compilations. E.1. 4 Librar ies Object files in ".objn format mayor may not be libraries. The result of a run of the code generator is an ".obj" which is not a library, although it is possible that such a file contains object code with corresponds to many subroutines. The main difference between ".obj" files which are libraries and those which are not libraries is that the linker includes all of the object code from non-library input files but only that object code which is referenced from library input files. The determination of what is referenced is made based on unresolved external code references in previous input files to the linker. Therefore the order that files are presented to the linker is important. When linking FORTRAN programs, the two run time libraries provided with the system must be among the input files to the linker. One of these libraries is paslib.obj which is a library which is common for SVS Pascal, SVS FORTRAN, and SVS C. It contains a variety of low level support routines used by all three Page 164 FORTRAN Reference Manual Operating the SVS FORTRAN System Appendix E languages. It must be linked as the last w.objW input file to the linker. The other library is ftnlib.obj which contains run time support specific to the FORTRAN language and which must be linked as the second to last w.obj" input file to the linker. E.l.S Error Messages The FORTRAN system contains a file of compile time error messages. If this file is given the appropriate name, the compiler will generate English error messages along with error numbers. If not, the compiler will only give error numbers. The FORTRAN system also contains a file of run time error messages. If this file is given the appropriate name, most run time errors detected in FORTRAN application programs will print English error messages in addition to the run time error number. The names to be given to these two error message files differs from one implementation to another and can be found by referring to the following appendix. E.2 Command Line Directives and Compiler Options The FORTRAN compiler front end is invoked to compile a source file named "prog.for w (other file name endings required on other systems) with a command line of the form: fortran prog.for {options ••• } Any number of command line options may appear and they may appear in any order. The possible command line options are: +q -q Show more (-q) or less (+q) information on the progress of the compile to the user. The default setting varies among different implementations. +p -p Prompt (+p) or don't prompt (-p) to the standard input in the case of a compile time error. The default setting varies among different implementations. Prompting mode is useful so that error messages do not fly off CRT screens but is awkward when compiling in background mode. +x Generate a cross reference in the listing file. Same as setting the $XREF option (see Chapter 13) • +c72 Truncate input lines to 72 columns. Same as setting the $COL72 option (see Chapter 13). +f -f Generate code for the Sky floating point hardware board (+f) or generate code for software floating point (-f). This option is only enabled in FORTRAN Reference Manual Page 165 Appendix E Operating the SVS FORTRAN System systems which support the Sky board and will result in an error if not enabled. The default is -f, no floating point hardware. Note: If the Sky floating point hardware interface is to be used,. the entire program must be compiled with the +f flag set and the resulting object code must be linked with sky.paslib.obj instead of paslib.obj. -lfname Create a listing file of the the file named fname. source -efname Place a summary of the file named fname. -ifname Name the ".i" file fname. If this option is not provided, the ".i" file when compiling a source program named prog.for is named progoi. compile time program in errors on Under certain operating systems the code generator is directly invoked by the FORTRAN compiler front end. In this case, there is an additional command line option. -of name Name the ".obj" file fname. If this option is not provided, the ".obj" file when compiling a source program named prog.for is named prog.obj. Under systems in which the code generator is not directly invoked by the FORTRAN compiler front end, the code generator is invoked using a command of the form: code prog.i {optionalfname} where leaving off the optional file name results in an output file named prog.obj. If the optional file name is provided, the output file is named optionalfname. See the appendix which follows for a description line arguments and options related to the linker. E.l of command Linking Programs which Utilize Pascal and C There are certain rules which must be observed by programmers wishing to combine object code compiled under more than one language processor. Throughout the following discussion, Pascal, FORTRAN, and C refer to the SVS implementations of these languages. Page 166 FORTRAN Reference Manual Operating the SVS FORTRAN System Appendix E E.3.l What Language must Supply the Main Program In all cases in which FORTRAN code is present, the main program must be FORTRAN. In the case where Pascal and C are to be present, either language may supply the main program. If the C system is not SVS C, then the main program must be Pascal. E.3.2 Referring to the Command Line Arguments In all cases in which the command line arguments are to be referenced from C, C must provide the main program. This is a consequence of the fact that command line arguments are "parameters" to the C main routine. Command line arguments are available from Pascal and FORTRAN regardless of which language provides the main program. E.3.3 Dynamic Memory Allocation and Deallocation A program may utilize the C library memory allocation and deallocation package (malloc, free, etc.) providing that Pascal components of the program do not call release. Similarly, Pascal components should not call release if FORTRAN components performing any I/O are present. If the C system is not SVS C, then the C routines must not utilize any dynamic memory. allocation or deallocation directry-or through the operating system run time library. E.3.4 Paramete~ Conventions The calling convention in C is such that parameters are pushed in "reverse" order from the order in which they appear and the calling routine is responsible for popping parameters off the stack after the call returns. Pascal and FORTRAN push parameters in order and the exit code of the called routines is responsible for popping off its parameters. Pascal contains a "cexternal" declaration (similar to Pascal "external") which generates calls to C routines in which the parameters are popped off at the calling site after the subroutine returns. The parameters must appear in reverse order in the Pascal call as compared to the order expected by C. There is no direct language support for calling C from FORTRAN or Pascal and FORTRAN from C, but parameterless routines or assembly language interfacing routines can be utilized for these purposes. It is often easiest to go through Pascal when calling C from FORTRAN (a complete explanation of which can be found in the Pascal Reference Manual) • FORTRAN Reference Manual Page 167 Operating the SVS FORTRAN System E.3.4.1 Appendix E Calling FORTRAN from Pascal It is straight forward to call FORTRAN subroutines from Pascal. The called routines should be declared to be external in the Pascal compilation with formal parameter declarations which match PORTRAN parameter conventions. In particular, Pascal var parameters will match the FORTRAN call by reference convention. If the receiving FORTRAN routine expects a character parameter, it will be necessary to pass the length of the packed array of char as an explicit two byte value parameter (as described in the parameter passing section of the FORTRAN reference manual). Note: Pascal strings are not compatible with the FORTRAN character datatype. E.3.4.2 Calling Pascal from FORTRAN When calling an external routine from FORTRAN, it is merely invoked without any special declaration. This called routine may have been written in Pascal. In the event that it is, the routine should be written with formal parameters declared in the manner which is consistent with what FORTRAN would expect from a receiving routine written in FORTRAN. Pascal formal parameter declarations are adequate for expressing all of the interfaces expected by FORTRAN calling sites. E.3.4.) Calling C from FORTRAN FORTRAN programs call external routines without declaration as functions in expressions and as procedures in CALL statements. fORTRAN generally passes all parameters by reference, so the receiving routine should expect pointer parameters. Assuming a fORTRAN function call as illustrated below: 100 INTEGER I,J DOUBLEPRECISION 0 I a CFUNCT2(I,J,D) the receiving C function might be as follows cfunct2(d,j,i) int *i,*j: double *d·, { if (*d =a 0.0) return(*i+*j): else return(*i-*j): } An assembly language interfacing routine, called a "wrapper", will be necessary to provide a proper interface between the calling site and the C routine since FORTRAN has no way of knowing to pop the parameters off at the calling site. The wrapper would be as follows: Page 168 FORTRAN Reference Manual Operating the SVS FORTRAN System Appendix E .text .globl .globl CFUNCT2: movl jsr addl movl rts savera: .bss CFUNCT2 cfunct2 sp@+,savera cfunct2 t12,sp savera,-sp@ • • • + 4 There are several important points to note: The FORTRAN external reference is in upper case letters whereas the C entry point is in the same upper/lower case letters as specified in the C source code. Under some operating systems, the C entry point will require a prepended underscore to adhere to the conventions in that environment. The wrapper will not work if the interlanguage call is recursive, although a more sophisticated version of the wrapper can be made to work in this situation. The primary role of the wrapper is to pop off the 12 bytes of parameters (3 pointers) which PORTRAN expects to be popped off by the called routine and which C expects to be popped off by the caller. The above procedure is not guaranteed ~ work with £ systems other than SVS C since the parameter, register, and return value location-conventIons are not necessarily the same in other C implementations. In general, these incompatibilities can be adjusted for by enhancin9 the wrapper. The exact syntax of the assembly language will vary from system to system. In general the object code for wrappers is linked into the executable program at the last linkin9 step of the compile. Normally, a wrapper is required for each FORTRAN to C call. Is is particularly difficult to pass character variables from FORTRAN to C since C has no method of receiving a two byte value parameter correspondin9 to the length portion of the character parameter. E.3.4.4 Calling PORTRAN from C When calling FORTRAN from C, the actual parameters should evaluate to pointers to properly map into the FORTRAN reference parameter conventions. There is no way to tell the C system that an external reference is to a non C routine. Therefore, assuming that i and j are 4 byte integers and that d is an eight byte floating point variable, a C call of the form: i = ifunc(&d,&j,&i)1 would require an assembly language "wrapper" of the form: FORTRAN Reference Manual Page 169 Appendix E Operating the SVS FORTRAN System .text .globl .globl ifunc: movl jsr subl movl rts .bss savera: • s • + ifunc IFUNC sp@+,savera IFUNC tl2,sp savera,-sp@ 4 to call a FORTRAN function declared with the header FUNCTION IFUNC(I,J,O) DOUBLE PRECISION 0 INTEGER I,J The important items to note are: FORTRAN entry point is in upper case, C external reference is in the same case as the programmer specified. The .globl for the C entry point may need a prepended underscore on some operating systems. The wrapper will not work if the inter language call is recursive. The C calling site expects to pop off 12 bytes of parameters after the call returns (3 pointers), but the FORTRAN function has already popped off the parameters. Therefore, the wrapper decrements the stack pointer by the amount the calling site expects to pop off. The exact syntax of the assembly language will vary from system to system. In general the object code for wrappers is linked into the executable program at the last linking step of the compile. Normally, a wrapper is required for each C to FORTRAN call. The above procedure will not work with C ssstems other than SVS C -oicause- other C systems expect carIed-su [Outlnes-tO preserve different registers then FORTRAN functions preserve. In this case, the wrapper must be enhanced to preserve the registers required by the calling C language subroutine. E.3.5 Run Time Libraries When linking multiple languages, the last input file provided to the linker must always be paslib.obj. Immediately preceding paslib.obj must be clib.obj and ftnlib.obj, in either order. The former must be present if C is present and the latter must be supplied if FORTRAN is contained in the program being linked. Page 170 FORTRAN Reference Manual Appendix E E.3.6 Operating the SVS FORTRAN System Upper and Lower Case External Naming Conventions It is the convention in Pascal and PORTRAN to upper case all external names except routine names which are declared cexternal in Pascal. These names are passed directly to the linker as they appeared in the cexternal declaration. In C, upper and lower case letters are distinct, so it is the convention to pass letters directly through as they were supplied by the programmer. For interfacing purposes, use upper case names in C, or use cexternal in Pascal, or use assembly language to bridge the naming conventions. FORTRAN Reference Manual Page 171 Operating the SVS FORTRAN System Page 172 Appendix E FORTRAN Reference Manual Appendix F CPM Operating System Specific Information Appendix F - CPM Operating System Specific Information Although the SVS FORTRAN system appears to be almost identical under a wide variety of operating systems, there are minor differences, particularly related to the linker and in operating procedures, among the various environments. This appendix will provide the implementation dependent details related to SVS FORTAN running under the CP/M-68K operating system. F.l Compiling ~ Simple Program Appendix E of this manual described in some detail the components of the SVS FORTRAN system. For most FORTRAN programs the follow i ng simple procedure will be compl ete 1 y adequa te for compiling, linking, and loading program: FORTRAN $l.FOR CODE $1.1 ULINKER -L Sl.O $1.0BJ FTNLIB.OBJ PASLIB.OEJ ERA $l.OBJ L068 -S -0 Sl.68K -T10l00 S.O Sl.0 CLIB To compile a FORTRAN program in a file named 'test.for', using the above supplied example submit file, type: FOR TEST The submit file assumes that the FORTRAN compiler front end (FORTRAN.68K), the code generator (CODE.68K), the linker (ULINKER.68K), and the libraries (FTNLIB.OBJ, PASLIB.OBJ, and CLIB.) reside on the current default disk and directory. You may wish to change this to reflect the location of these files on your system. FORTRAN Reference Manual Page 17 3 CPM Operating System Specific Information Appendix F The lines of the submit file do the following: The first two lines run the front end and code generator on files whose names are derived from the command line in which the submit file is invoked. The linker is run (in its simplest form, see below for more details) with -1 inhibiting a linkmap listing file, with output file $1.0, and with three input files, including the SVS supplied libraries. U1inker produces a file which is then linked to those CPM system calls which are utilized by the program in the 1068 step (which invokes the CPM system linker). P.2 Error Message Files The SVS FORTRAN system includes two files called ftncterr.src and ftnrterr.src which should be placed in either the a: or b: drive. This will allow the compiler to display English messages for errors which it detects and will allow the FORTRAN run time system to display English error messages for most detected run time errors in application programs. F.3 U1inker Under CPM, u1inker is the SVS linker. The general operation of the linker is described in Appendix E. This section will describe in detail the modes of operation of u1inker and its load map listing option. P.3.1 U1inker Inputs U1inker links object code in ".obj" format, including libraries. In addition, u1inker accepts input from the command line or interactively as described below. P.3.2 U1inker Outputs U1inker creates partially linked object code in CPM ".0" format as its primary output. Optionally, u1inker can produce a listing file which is a load map of global entry points in the created ".0" file. The form of this map and information contained in it is best described by the following example with subsequent explanations: Page 174 FORTRAN Reference Manual Appendix F CPM Operating System Specific Information Example of U1inker Listing File I, Linking segment • I (4310) Linking segment F77RTS' (3376) MC68000 CPM Object-Code Formatter 05-0ct-83 File: sma11f.o Memory map for segment ONE TWO SMALLF $START , FWRITE - ':PREAD - ':PREAO I OOOOOE 000120 000174 000174 0001C4 0001F2 ONE TWO SMALLF $START , FWRITE 001194 00119E Memory map for segment "_F77RTS' $2000000 - ERROR $5000000 - FOUTPUTR $6000000 - FINPUTRE 0011B4,' F77RTS 0011DA,'-F77RTS 001222,':F77RTS 001E12,'_F77RTS Static Data Areas: I'F77RTI IASC I ONE SMALLF TWO No: o. at at at at at 000000 0003C4 000000 0003BO 0003B8 Segment: I 1. "_F77RTS' BSS 8SS Data BSS BSS area area area area area relative, relative, relative, relative, relative, size 0003BO size 000008 size oooooe size 000008 size oooooe Size: 001006 000030 Start Loc = 000174 Code Size = 001E06 Global Size = 000000 FORTRAN Reference Manual Page 175 CPM Operating System Specific Information Appendix F Explanation of Ulinker Listing File The listing file was generated from the gram: following FORTRAN pro- subroutine one common/abc/icomml,icomm2 data ii,jj,kk/l,2,3/ write(*,*)ii,jj,kk icomml • 99 icomm2 • 999 end subroutine two common/abc/icomml,icomm2 ii • 1 jj • 2 kk • 3 write(*,*)ii,jj,kk write(*,*)icomml,icomm2 end program smallf i • 17 j • 33 * i write(*,*)i,j call one call two end The segment named by 8 blanks had 4310 (decimal) bytes in it. The segment named , F77RTS had 3376 (decimal) bytes in it. Under CPM there is no reason for programmers to explicitly deal with segments, since ulinker handles this automatically. There were a large number of entry points in the linked files, most of which were extracted from the run time libraries, only a few of which are shown above and the remainder have been omitted in order to keep the example listing short. Three of these entry points are recognizable as user procedure names. The addresses of these entry points are given in hex and are text area relative, but will be further relocated ~ the 1068 step of the compilation: --,ne--relative addresses (dTitance be ween-them) WIII remain intact through the 1068 step. For each FORTRAN procedure, for each FORTRAN common area, and for the FORTRAH run time system there is a static data area listed. Each such data area is mapped to the data or bss area depending upon whether the area is initialized at compile time using the data statement. Note: an area which is partially initialized using data statements is mapped to the data (as opposed to bss) Page 176 FORTRAN Reference Manual Appendix F CPM Operating System Specific Information area, even if the area is large and only sparsely initialized. Initialized data areas are represented in the CPM object file format as an image and large data areas which are initialized result in large object files. In the example, the common area is indicated by having a data area name which begins and ends in slashes. Sizes and locations of these data area listings are in hex and relative to the start of the data or bss area as appropriate. F.3.3 Running Ulinker from the Command Line The command line form of running u1inker is: ulinker 1istfname outputfname inputfname {inputfname ••• } where the optional listing file is created on a file named 1istfname providing that 1istfname is not equal to -1 (no listing file to be created directive). The command line arguments are positional. No file name suffixes are enforced by u1inker in this mode so complete file names must be entered. F.3.4 Running U1inker Interactively It is often not convenient or not possible to have a command line which is long enough to have all of the input files listed. In this event, u1inker can be run interactive. Execute u1inker without any command line arguments and it prompts: Listing file ~ Any file name provided creates the listing file. Enter just return to suppress the optional listing file. The next prompt is: Output file [.0] Ulinker requires an output file. If the file name provided does not end in w.o·, ulinker will append this file name extension onto the name which is input. Following this prompt, u1inker will repeatedly prompt: ~ Input file [.obj] for its input files, until a plain return is typed, indicating that the input file list is completed. U1inker will append the ·.obj· suffix onto input file names if it is not supplied by the user. Running in this mode, there is no limit on the number of input files which ulinker can process. FORTRAN Reference Manual Page.l71 CPM Operati~g P.3.S System Specific Information Appendix P Running Ulinker with Standard Input Redirected With many input files, it is most convenient to operate ulinker in its interactive mode with standard input redirected. Por example, run ulinker as follows: ulinker
Source Exif Data:File Type : PDF File Type Extension : pdf MIME Type : application/pdf PDF Version : 1.3 Linearized : No XMP Toolkit : Adobe XMP Core 4.2.1-c043 52.372728, 2009/01/18-15:56:37 Create Date : 2013:05:03 08:40:27-08:00 Modify Date : 2013:05:03 08:16:56-07:00 Metadata Date : 2013:05:03 08:16:56-07:00 Producer : Adobe Acrobat 9.53 Paper Capture Plug-in Format : application/pdf Document ID : uuid:7d6eb343-9129-c342-825a-46481cc243cd Instance ID : uuid:8985f920-8963-c542-a4cf-0022cf70b3d4 Page Layout : SinglePage Page Mode : UseNone Page Count : 192EXIF Metadata provided by EXIF.tools