- Forward declaration
In
computer programming , a forward declaration is a declaration of a variable or function which the programmer has not yet given a completedefinition .In C, the two lines above represent forward declarations of an
array and a function of one parameter, respectively. (The latter is also afunction prototype .) After processing these declarations, thecompiler would allow the programmer to refer to the entitieselements
andfoo
in the rest of the program; but at some point the programmer would still have to provide "definitions" for the declared entities:In Pascal and other Wirth programming languages, it is a general rule that all entities must be declared before use. In C, the same general rule applies, but with an exception for undeclared functions. Thus, in C it is possible (although unwise) to implement a pair of mutually recursive functions thus:
In Pascal, the same implementation requires a forward declaration of
second
to precede its use infirst
. Without the forward declaration, the compiler will produce an error message indicating that theidentifier second
has been used without being declared.Forward reference
The term forward reference is sometimes used as a
synonym of "forward declaration". [ [http://msdn2.microsoft.com/en-us/library/15k227ta(VS.71).aspx MSDN: Converting to a Forward-Reference Class Type] ] However, more often it is taken to refer to the actual "use" of an entity before any declaration; that is, the first reference tosecond
in the code above is a forward reference. [ [http://pages.cs.wisc.edu/~fischer/cs536.s07/lectures/Lecture25.4up.pdf] ] [ [http://www.codeguru.com/cpp/tic/tic0103.shtml Thinking in C++: Inlines & the compiler] ] Thus, we may say that because forward declarations are mandatory in Pascal, forward "references" are prohibited.An example of (valid) forward reference in
C++ :In this example, there are two references to
myValue
before it is declared. C++ generally prohibits forward references, but they are allowed in the special case of class members. Since the member functionaccessor
cannot be compiled until the compiler knows the type of the member variablemyValue
, it is the compiler's responsibility to remember the definition ofaccessor
until it seesmyValue
's declaration.Permitting forward reference can greatly increase the complexity and memory requirements of a compiler, and generally prevents the compiler from being implemented in one pass.
References
Wikimedia Foundation. 2010.