Why do some languages ​​require a function to be declared in code before calling?

Suppose you have this pseudo code

do_something(); function do_something(){ print "I am saying hello."; } 

Why do some programming languages ​​require calling do_something () to display below the function declaration to run the code?

+4
source share
2 answers

Programming languages ​​use a symbol table to store various classes, functions, etc. that are used in the source code. Some languages ​​are compiled in one pass, causing the characters to exit the character table as soon as they are used. Others use two passes, where the first pass is used to populate the table, and then the second is used to search for records.

+7
source

Most languages ​​with a static type system are designed to use the definition before use , which means that there must be some function declaration before the call so that the call can be checked (for example, it is a function that receives the correct number and types of arguments). Such a design helps both the person and the compiler reading the program: everything that you see is already defined. The ease of reading and the popularity of single-pass compilers may explain the popularity of this design rule.

Unfortunately, the definition before use doesn’t work well with mutual recursion, and therefore the language developers have resorted to an ugly hack in which you have

  • Declaration (sometimes called a "direct declaration" from a keyword in Pascal)
  • Using
  • Definition

You see the same type-level phenomenon in C in the form of an "incomplete struct declaration".

Around 1990, some language developers found that a one-pass compiler without an abstract syntax tree should be a thing of the past, and two very nice projects from this era: Modula-3 and Haskell got rid of the definition before use: in these languages, any specific function or variable visible in its entire area, including parts of the program, textually before the definition. In other words, mutual recursion is the default for both types and functions. Well in them, I say, these languages ​​do not have ugly and unnecessary statements for the future.

Why [has a definition before use]?

  • It's easy to write a one-pass compiler in 1975.

  • without a definition before use, you need to think more about mutual recursion, especially about mutually recursive type definitions.

  • Some people find it easier to read code.

+2
source

Source: https://habr.com/ru/post/1299622/


All Articles