# Forward declaration

> Mediated Wiki article. Canonical URL: https://mediated.wiki/source/Forward_declaration
> Markdown URL: https://mediated.wiki/source/Forward_declaration.md
> Source: https://en.wikipedia.org/wiki/Forward_declaration
> Source revision: 1356893544
> License: Creative Commons Attribution-ShareAlike 4.0 International (https://creativecommons.org/licenses/by-sa/4.0/)

{{Short description|Declaration of an identifier in computer programming}}
In [computer programming](/source/computer_programming), a '''forward declaration''' is a [declaration](/source/declaration_(computer_science)) of an [identifier](/source/Identifier_(computer_programming)) (denoting an entity such as a type, a variable, a constant, or a function) for which the programmer has not yet given a complete [definition](/source/definition).

It is required for a [compiler](/source/compiler) to know certain properties of an identifier (size for [memory allocation](/source/memory_allocation), [data type](/source/data_type) for [type checking](/source/Type_system), such as [type signature](/source/type_signature) of functions), but it isn't required to know some other details, like the particular value it holds (in case of variables or constants) or definition (in the case of functions). This is particularly useful for [one-pass compiler](/source/one-pass_compiler)s and [separate compilation](/source/separate_compilation).

Forward declaration is used in languages that require declaration before use; it is necessary for [mutual recursion](/source/mutual_recursion) in such languages, as it is impossible to define such functions (or data structures) without a forward reference in one definition: one of the functions (respectively, data structures) must be declared first. It is also useful to allow flexible code organization, for example if one wishes to place the main body at the top, and called functions below it.

In other languages forward declarations are not necessary, which generally requires instead a [multi-pass compiler](/source/multi-pass_compiler) and for some compilation to be deferred to [link time](/source/link_time). In these cases identifiers must be defined (variables initialized, functions defined) before they can be employed during runtime without the need for pre-definition in the [source code](/source/source_code) for either compilation or interpretation: identifiers do not need to be immediately resolved to an existing entity.

==Examples==
A basic example in C is:
<syntaxhighlight lang=c>
void printThisInteger(int);
</syntaxhighlight>

In [C](/source/C_(programming_language)) and [C++](/source/C%2B%2B), the line above represents a forward declaration of a [function](/source/subroutine) and is the [function's prototype](/source/function_prototype). After processing this declaration, the [compiler](/source/compiler) would allow the program code to refer to the entity <code>printThisInteger</code> in the rest of the program. The definition for a function must be provided somewhere (same file or other, where it would be the responsibility of the linker to correctly match references to a particular function in one or several object files with the definition, which must be unique, in another):

<syntaxhighlight lang="c">
void printThisInteger(int x) {
   printf("%d\n", x);
}
</syntaxhighlight>

Variables may have only forward declaration and lack definition. During compilation time these are initialized by language specific rules (to undefined values, 0, NULL pointers, ...). Variables that are defined in other source/object files must have a forward declaration specified with a keyword <code>extern</code>:

<syntaxhighlight lang="c">
int foo; //foo might be defined somewhere in this file
extern int bar; //bar must be defined in some other file
</syntaxhighlight>

In [Pascal](/source/Pascal_(programming_language)) and other [Wirth](/source/Niklaus_Wirth) programming languages, it is a general rule that all entities must be declared before use, and thus forward declaration is necessary for mutual recursion, for instance. In C, the same general rule applies, but with an exception for undeclared functions and incomplete types. Thus, in C it is possible (although unwise) to implement a pair of [mutually recursive](/source/mutual_recursion) functions thus:

<syntaxhighlight lang=c>
int first(int x) {
    if (x == 0)
        return 1;
    else
        return second(x-1); // forward reference to second
}

int second(int x) {
    if (x == 0)
        return 0;
    else
        return first(x-1); // backward reference to first
}
</syntaxhighlight>

In Pascal, the same implementation requires a forward declaration of <code>second</code> to precede its use in <code>first</code>. Without the forward declaration, the compiler will produce an [error message](/source/error_message) indicating that the [identifier](/source/identifier) <code>second</code> has been used without being declared.

==Classes==
In some object-oriented languages like [C++](/source/C%2B%2B) and [Objective-C](/source/Objective-C), it is sometimes necessary to forward-declare classes. This is done in situations when it is necessary to know that the name of the class is a type, but where it is unnecessary to know the structure.

In C++, classes and structs can be forward-declared like this:
<syntaxhighlight lang="cpp">
class MyClass;
struct MyStruct;
</syntaxhighlight>
In C++, classes can be forward-declared if you only need to use the pointer-to-that-class type (since all object pointers are the same size, and this is what the compiler cares about). This is especially useful inside class definitions, e.g. if a class contains a member that is a pointer (or a reference) to another class.

Forward-declaration is used to avoid unnecessary coupling which help reducing compilation time by reducing the number of header inclusion. This has a triple advantage: 
* reduce the number of files opened by #include (hence the number of [operating system](/source/operating_system) calls)
* reducing the volume of the pre-processed files (as the header is not included)
* reducing recompilation impact when the forward declared class is modified.

Forward declaration of a class is not sufficient if you need to use the actual class type, for example, if you have a member whose type is that class directly (not a pointer), or if you need to use it as a base class, or if you need to use the methods of the class in a method.

In Objective-C, classes and protocols can be forward-declared like this:
<syntaxhighlight lang="objc">
@class MyClass;
@protocol MyProtocol;
</syntaxhighlight>
In Objective-C, classes and protocols can be forward-declared if you only need to use them as part of an object pointer type, e.g. {{mono|MyClass *}} or {{mono|id<MyProtocol>}}. This is especially useful inside class definitions, e.g. if a class contains a member that is a pointer to another class; to avoid [circular reference](/source/circular_reference)s (i.e. that class might also contain a member that is a pointer to this class), we simply forward-declare the classes instead.

Forward declaration of a class or protocol is not sufficient if you need to subclass that class or implement that protocol.

==Forward reference==
The term '''forward reference''' is sometimes used as a synonym of ''forward declaration''.<ref>[http://msdn2.microsoft.com/en-us/library/15k227ta(VS.71).aspx MSDN: Converting to a Forward-Reference Class Type]</ref> However, more often it is taken to refer to the actual ''use'' of an entity before any declaration; that is, the first reference to <code>second</code> in the code above is a forward reference.<ref>http://pages.cs.wisc.edu/~fischer/cs536.s07/lectures/Lecture25.4up.pdf {{Bare URL PDF|date=March 2022}}</ref><ref>{{Cite web |url=http://www.fi.muni.cz/usr/jkucera/tic/tic0103.html |title=Thinking in C++: Inlines & the compiler |access-date=2015-10-26 |archive-date=2016-03-04 |archive-url=https://web.archive.org/web/20160304075856/http://www.fi.muni.cz/usr/jkucera/tic/tic0103.html |url-status=dead }}</ref> Thus, we may say that because forward declarations are mandatory in Pascal, forward ''references'' are prohibited.

An example of (valid) forward reference in [C++](/source/C%2B%2B):

<syntaxhighlight lang="cpp">
class C {
public:
   void mutator(int x) { myValue = x; }
   int accessor() const { return myValue; }
private:
   int myValue;
};
</syntaxhighlight>

In this example, there are two references to <code>myValue</code> before it is declared. C++ generally prohibits forward references, but they are allowed in the special case of class members. Since the member function <code>accessor</code> cannot be compiled until the compiler knows the type of the [member variable](/source/member_variable) <code>myValue</code>, it is the compiler's responsibility to remember the definition of <code>accessor</code> until it sees <code>myValue</code>'s declaration.

Permitting forward references can greatly increase the complexity and memory requirements of a compiler, and generally prevents the compiler from being implemented in [one pass](/source/one-pass_compiler).

==References==
<references/>

Category:Programming constructs
Category:Articles with example C code

---
Adapted from the Wikipedia article [Forward declaration](https://en.wikipedia.org/wiki/Forward_declaration) by Wikipedia contributors ([contributor history](https://en.wikipedia.org/wiki/Forward_declaration?action=history)). Available under [Creative Commons Attribution-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-sa/4.0/). Changes may have been made.
