A basic example in C is: void printThisInteger(int); In
C and
C++, the line above represents a forward declaration of a
function and is the
function's prototype. After processing this declaration, the
compiler would allow the program code to refer to the entity printThisInteger 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): void printThisInteger(int x) { printf("%d\n", x); } 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 extern: int foo; //foo might be defined somewhere in this file extern int bar; //bar must be defined in some other file In
Pascal and other
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 functions thus: 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 } In Pascal, the same implementation requires a forward declaration of second to precede its use in first. Without the forward declaration, the compiler will produce an
error message indicating that the
identifier second has been used without being declared. ==Classes==