MAIN statement indicates the beginning of the MAIN program block.
Program Block |
A number of statements |
An executable 4GL program can have no more and no less than one MAIN program block. It is usually used to call the functions and reports that are located within the same program module or in other program modules and libraries. The example below illustrates how the functions within the same program module are called in the MAIN program block:
MAIN
…
CALL first_finction()
CALL second_function()
…
END MAIN
FUNCTION first_finction()
…
END FUNCTION
FUNCTION second_function()
…
END FUNCTION
The MAIN statement can be used only as the first statement of the MAIN program block. It cannot be used in another 4GL or SQL statement. The END MAIN keywords are required, they mark the end of the MAIN program block. The program is terminated, when 4GL encounters the END MAIN program block. The program can terminate before the END MAIN keywords, if 4GL encounters the EXIT PROGRAM statement.
The MAIN program block can include any 4GL statements and supported SQL statements. Typically, it includes the DEFINE statement which declares the variables local to this program block. It can also include the DATABASE statement specifying the current database and the DEFER statement preventing the application from termination.
If you try to compile a program without the MAIN block, it will be compiled successfully.
If you try to run the compiled application that has no MAIN block, you will get the runtime error – -102006. Undefined function:
Variables declared by means of the DEFINE statement within the MAIN block are local to this MAIN program block, they cannot be referenced in other program blocks like FUNCTION or REPORT.
The variables declared before the MAIN keyword are module variables and can be referenced in the MAIN program block and in all the program blocks within this program module. The variables in the GLOBALS file have the scope of reference that is larger than one module. If you define variables with the same name as local, module and global variables, they will be used according to such precedence:
DEFER statement can occur only within the MAIN program block.
DATABASE statement that is located before the MAIN program block specifies the default database. This database becomes the current database if no other DATABASE statement is present within the MAIN block. A DATABASE statement within the MAIN block specifies the current database, this statement must occur after the DEFINE statement of the MAIN program block, if it is present.