Search code examples
fortran

constant number before a statement in fortran code


I came across something and I am unable to find any explanation for it, consider the following two code snippets.

THIS RUNS

Program Hello

implicit none

print *, "hello world"

1 print *, "one"

print *, "bye world"

End Program Hello

output:
hello world
one
bye world

THIS DOES NOT COMPILE

Program Hello

implicit none

print *, "hello world"

1 
print *, "one"

print *, "bye world"

End Program Hello
error:\
main.f95:16:1:\
   16 | 1\
      | 1\
Error: Statement label without statement at (1)

Anyone knows what is happening here? Why does the first one compile and run?

PS: it is not useful code, however I saw "1 continue" in some Fortran code, and was just wondering what that even achieves?

EDIT: SO it is likely a statement label, How are Fortran statement labels used? are they purely cosmetic or actually provide some usage?


Solution

  • The 1 here is not a numeric constant; it is a statement label. (Recall that expressions like the actual constant 1 cannot appear in arbitrary places, or as the only part of a statement as can be found in some other languages.)

    A statement label (Fortran 2018 6.2.5):

    provides a means of referring to an individual statement

    That's it: it's a label to say that the print statement in the first example can be referred to be a reference to the label 1.

    A statement label consists of between one and six digits, at least one of which is not a zero. Within a scope, they must be unique (ignoring leading zeros).

    A label must be followed by a statement with non-blanks. This makes

    1
    

    invalid.

    Not all statements may be labelled, and not all statements are usefully labelled. Labels are meaningful to the program only in the following cases:

    1. As a statement to be "jumped" to (go to, etc.)
    2. Necessarily as part of a format statement (so it can be referenced)
    3. In a non-block DO construct (obsolete in Fortran 2018)

    In other cases a statement label is meaningful only to programmers (say as documentation).

    1 continue
    

    is commonly used in cases like the non-block DO:

    do 1 i=1, 10
    1 continue
    

    (but we don't do these any longer).

    Or similarly as a do-nothing jump target:

    read(unit, err=1)
    ...
    1 continue
    

    (if we aren't using iostat=... which we should).