Declaration (computer programming): Difference between revisions
Magioladitis (talk | contribs) |
width |
||
(35 intermediate revisions by 25 users not shown) | |||
Line 1: | Line 1: | ||
{{Short description|Programming language construct specifying an identifier's properties}} |
|||
{{cleanup|reason=Too many examples of unclear relevancy; not enough references; problematic mentions of header files and multiple declarations|date=December 2013}} |
{{cleanup|reason=Too many examples of unclear relevancy; not enough references; problematic mentions of header files and multiple declarations|date=December 2013}} |
||
In [[computer programming]], a '''declaration''' is a [[language construct]] specifying [[Identifier (computer programming)|identifier]] properties: it declares a word's (identifier's) meaning.<ref name="c11">"A declaration specifies the interpretation and attributes of a set of identifiers. A ''definition'' of an identifier is a declaration for that identifier that: |
|||
In [[programming languages]], a '''declaration''' specifies the [[identifier]], [[type system|type]], and other aspects of language elements such as [[variable (programming)|variables]] and [[subroutine|functions]]. It is used to announce the existence of the element to the [[compiler]]; this is important in many [[strongly typed]] languages (such as [[C (programming language)|C]]) that require variables and their types to be specified with a declaration before use, and is used in [[forward declaration]].<ref>{{cite web |
|||
* for an object [variable or constant], causes storage to be reserved for that object; |
|||
| accessdate = 2011-06-08 |
|||
* for a function, includes the function body; |
|||
* for an enumeration constant, is the (only) declaration of the identifier; |
|||
* for a typedef name, is the first (or only) declaration of the identifier." |
|||
C11 specification, 6.7: Declarations, paragraph 5.</ref> Declarations are most commonly used for [[subroutine|functions]], [[Variable (computer science)|variables]], [[Constant (computer programming)|constants]], and [[Class (computer programming)|classes]], but can also be used for other entities such as [[Enumerator (computer science)|enumerations]] and type definitions.<ref name="c11"/> Beyond the name (the identifier itself) and the kind of entity (function, variable, etc.), declarations typically specify the [[data type]] (for variables and constants), or the [[type signature]] (for functions); types may also include dimensions, such as for [[Array data structure|array]]s. A declaration is used to announce the existence of the entity to the [[compiler]]; this is important in those [[strongly typed]] languages that require functions, variables, and constants, and their types to be specified with a declaration before use, and is used in [[forward declaration]].<ref>{{cite web |
|||
| access-date = 2011-06-08 |
|||
| author = Mike Banahan |
| author = Mike Banahan |
||
| location = http://publications.gbdirect.co.uk/c_book/ |
|||
| publisher = GBdirect |
| publisher = GBdirect |
||
| title = 2.5. Declaration of variables |
| title = 2.5. Declaration of variables |
||
| quote = [A] declaration [...] introduces just the name and type of something but allocates no storage[...]. |
| quote = [A] declaration [...] introduces just the name and type of something but allocates no storage[...]. |
||
| url = http://publications.gbdirect.co.uk/c_book/chapter2/variable_declaration.html}}</ref> |
| url = http://publications.gbdirect.co.uk/c_book/chapter2/variable_declaration.html}}</ref> The term "declaration" is frequently contrasted with the term "definition",<ref name="c11"/> but meaning and usage varies significantly between languages; see below. |
||
Declarations are particularly prominent in languages in the [[ALGOL]] tradition, including the [[BCPL]] family, most prominently [[C (programming language)|C]] and [[C++]], and also [[Pascal (programming language)|Pascal]]. [[Java (programming language)|Java]] uses the term "declaration", though Java does not require separate declarations and definitions. |
|||
In the [[BCPL]] family languages such as [[C++]] and [[Java (programming language)|Java]], it can also specify the [[variable (programming)|variable]]'s [[dimension]]s to declare a scalar, array or matrix. In this family, "pure" declarations (announcing the existence and properties of the element, commonly called simply "declarations") and ''definitions'' (declarations that provide the actual [[implementation]] in the case of functions, and [[initialization (programming)|initialization]] in the case of variables) can be made independent of each other. |
|||
==Declaration vs. definition== |
|||
== Declarations and Definitions == |
|||
One basic dichotomy is whether or not a declaration contains a definition: for example, whether a variable or constant declaration [[initialization (programming)|specifies its value]], or only its type; and similarly whether a declaration of a function specifies the body ([[implementation]]) of the function, or only its type signature.<ref name="c11"/> Not all languages make this distinction: in many languages, declarations always include a definition, and may be referred to as either "declarations" or "definitions", depending on the language.{{efn|For example, Java uses "declaration" (class declaration, method declaration), while Python uses "definition" (class definition, function definition).<ref>[https://docs.python.org/2/reference/compound_stmts.html 7. Compound statements], ''The Python Language Reference''</ref>}} However, these concepts are distinguished in languages that require declaration before use (for which forward declarations are used), and in languages where interface and implementation are separated: the interface contains declarations, the implementation contains definitions.{{efn|This distinction is observed in Pascal "units" (modules), and in conventional C and C++ code organization, which has [[header file]]s consisting largely of pure declarations, and [[source file]]s consisting of definitions, though this is not always strictly observed, nor enforced by the language.}} |
|||
In the C-family of programming languages, declarations are made in [[header file]]s, which are included in other source files that reference and use these declarations, but don't have access to the definition. This creates an interface between the declaration and implementation, thereby increasing code modularity.<ref>Torsten Seemann. "Code Modularity and the C Programming Language." http://www.csse.monash.edu.au/courseware/cse2304/hndtC.html: Monash University. Retrieved 2014-02-01. "</ref> A declaration is often used in order to access functions or variables defined in different source files, or in a [[Library (computing)|library]]. A mismatch between the definition type and the declaration type generates a compiler error. |
|||
In informal usage, a "declaration" refers only to a pure declaration (types only, no value or body), while a "definition" refers to a declaration that includes a value or body. However, in formal usage (in language specifications), "declaration" includes ''both'' of these senses, with finer distinctions by language: in C and C++, a declaration of a function that does not include a body is called a [[function prototype]], while a declaration of a function that does include a body is called a "function definition". In Java declarations occur in two forms. For public methods they can be presented in interfaces as method signatures, which consist of the method names, input types and output type. A similar notation can be used in the definition of [[abstract method]]s, which do not contain a definition. The enclosing class can be instantiated, rather a new derived class, which provides the definition of the method, would need to be created in order to create an [[Instance (computer science)|instance]] of the class. Starting with [[Java 8]], the lambda expression was included in the language, which could be viewed as a function declaration. |
|||
For variables, definitions assign values to an area of memory that was reserved during the declaration phase. For functions, definitions supply the function body. While a variable or function may be declared many times, it is typically defined once. Dynamic languages such as [[JavaScript]] or [[Python (programming language)|Python]] generally allow redefining of functions. |
|||
== Declarations and definitions == |
|||
In the C-family of programming languages, declarations are often collected into [[header file]]s, which are included in other source files that reference and use these declarations, but don't have access to the definition. The information in the header file provides the interface between code that uses the declaration and that which defines it, a form of [[information hiding]]. A declaration is often used in order to access functions or variables defined in different source files, or in a [[Library (computing)|library]]. A mismatch between the definition type and the declaration type generates a compiler error. |
|||
For variables, definitions assign values to an area of memory that was reserved during the declaration phase. For functions, definitions supply the function body. While a variable or function may be declared many times, it is typically defined once (in [[C++]], this is known as the [[One Definition Rule]] or ODR). |
|||
Dynamic languages such as [[JavaScript]] or [[Python (programming language)|Python]] generally allow functions to be redefined, that is, [[name binding|re-bound]]; a function is a variable much like any other, with a name and a value (the definition). |
|||
Here are some examples of declarations that are not definitions, in C: |
Here are some examples of declarations that are not definitions, in C: |
||
< |
<syntaxhighlight lang=C> |
||
extern char example1; |
extern char example1; |
||
extern int example2; |
extern int example2; |
||
void example3(void); |
void example3(void); |
||
</syntaxhighlight> |
|||
</source> |
|||
Here are some examples of declarations that are definitions, again in C: |
Here are some examples of declarations that are definitions, again in C: |
||
< |
<syntaxhighlight lang=C> |
||
char example1; /* Outside of a function definition it will be initialized to zero. */ |
|||
char example1; |
|||
int example2 = 5; |
int example2 = 5; |
||
void example3(void) |
void example3(void) { /* definition between braces */ } |
||
</syntaxhighlight> |
|||
</source> |
|||
== |
== Undefined variables == |
||
{{main|Undefined variable}} |
|||
In some programming languages an implicit declaration is provided the first time such a variable is encountered at [[compile time]]. In other languages such a usage is considered to be a fatal error, resulting in a diagnostic being issued. Some languages have started out with the implicit declaration behavior, but as they matured they provided an option to disable it (e.g. [[Perl]]'s "<code>use strict</code>" or [[Visual Basic]]'s "<code>Option Explicit</code>"). |
|||
In some programming languages, an implicit declaration is provided the first time such a variable is encountered at [[compile time]]. In other languages, such a usage is considered to be an error, which may result in a diagnostic message. Some languages have started out with the implicit declaration behavior, but as they matured they provided an option to disable it (e.g. [[Perl]]'s "<code>use strict</code>" or [[Visual Basic]]'s "<code>Option Explicit</code>"). |
|||
==See also== |
|||
Examples of how various programming language implementations respond to undefined variables are given below. Each code example is followed by an error message (if any). |
|||
* [[Scope (computer science)]] |
|||
==Notes== |
|||
[[CLISP]] (GNU CLISP 2.35) |
|||
{{Notelist}} |
|||
<source lang=Lisp> |
|||
(setf y x) |
|||
</source> |
|||
==References== |
|||
{{samp|*** - EVAL: variable X has no value}} |
|||
{{Reflist}} |
|||
==External links== |
|||
[[C Sharp (programming language)|C#]] ([[.NET Framework]]) |
|||
* [http://www.cprogramming.com/declare_vs_define.html Declare vs Define in C and C++], Alex Allain |
|||
<source lang=Csharp> |
|||
* [http://publications.gbdirect.co.uk/c_book/chapter8/declarations_and_definitions.html 8.2. Declarations, Definitions and Accessibility], ''The C Book,'' GBdirect |
|||
static void Main() |
|||
* [http://msdn.microsoft.com/en-us/library/0e5kx78b.aspx Declarations and Definitions (C++)], MSDN |
|||
{ |
|||
*:"Declarations tell the compiler that a program element or name exists. Definitions specify what code or data the name describes." |
|||
int y = x; |
|||
} |
|||
</source> |
|||
{{samp|The name 'x' does not exist in the current context}} |
|||
[[C (programming language)|C]] (GNU [[GNU Compiler Collection|GCC]] 3.4) |
|||
<source lang=C> |
|||
int main() |
|||
{ |
|||
int y = x; |
|||
return 0; |
|||
} |
|||
</source> |
|||
{{samp|foo.c: In function `main':}} |
|||
{{samp|foo.c:2: error: `x' undeclared (first use in this function)}} |
|||
{{samp|foo.c:2: error: (Each undeclared identifier is reported only once}} |
|||
{{samp|foo.c:2: error: for each function it appears in.)}} |
|||
[[JavaScript]] (Mozilla [[Firefox]] 1.0) |
|||
<source lang=Javascript> |
|||
y = x |
|||
</source> |
|||
{{samp|Error: x is not defined}} |
|||
{{samp|Source File: file:///c:/temp/foo.js}} |
|||
[[Standard ML]] (Standard ML of New Jersey v110.55) |
|||
val y = x; |
|||
{{samp|stdIn:1.9 Error: unbound variable or constructor: x}} |
|||
[[MUMPS]] |
|||
Set Y = X |
|||
{{samp|<UNDEF>}} |
|||
[[OCaml]] 3.08 |
|||
<source lang=Ocaml> |
|||
let y = x;; |
|||
</source> |
|||
{{samp|Unbound value x}} |
|||
[[Perl]] 5.8 |
|||
<source lang=Perl> |
|||
my $y = $x; |
|||
</source> |
|||
(no error) |
|||
<source lang=Perl> |
|||
use strict; |
|||
my $y = $x; |
|||
</source> |
|||
{{samp|Global symbol "$x" requires explicit package name at foo.pl line 2.}} |
|||
{{samp|Execution of foo.pl aborted due to compilation errors.}} |
|||
[[PHP]] 5 |
|||
<source lang=php> |
|||
$y = $x; |
|||
</source> |
|||
(no error) |
|||
<source lang=php> |
|||
error_reporting(E_ALL); |
|||
$y = $x; |
|||
</source> |
|||
{{samp|PHP Notice: Undefined variable: x in foo.php on line 3}} |
|||
[[Python (programming language)|Python]] 2.4 |
|||
<source lang=Python> |
|||
>>> x = y |
|||
Traceback (most recent call last): |
|||
File "foo.py", line 1, in ? |
|||
x = y |
|||
NameError: name 'y' is not defined |
|||
</source> |
|||
[[Ruby (programming language)|Ruby]] 1.8 |
|||
<source lang="ruby"> |
|||
irb(main):001:0> y = x |
|||
NameError: undefined local variable or method `x' for main:Object |
|||
from (irb):1 |
|||
from /usr/bin/irb:12:in `<main>' |
|||
</source> |
|||
[[Real Basic]] / [[Xojo]] |
|||
<source lang=vb> |
|||
Dim y As Integer |
|||
y = x |
|||
</source> |
|||
{{samp|Real Basic Error: Undefined method or property: x on line 2}} |
|||
[[VBScript]] (WSH 5.6) |
|||
<source lang=VB> |
|||
Dim y |
|||
y = x |
|||
</source> |
|||
(no error) |
|||
<source lang=VB> |
|||
Option Explicit |
|||
Dim y |
|||
y = x |
|||
</source> |
|||
{{samp|(3, 1) Microsoft VBScript runtime error: Variable is undefined: 'x'}} |
|||
==See also== |
|||
* [[Function prototype]] |
|||
* [[Scope (programming)]] |
|||
==References== |
|||
{{Reflist|2}} |
|||
[[Category:Programming language concepts]] |
[[Category:Programming language concepts]] |
Latest revision as of 19:21, 13 May 2024
This article may require cleanup to meet Wikipedia's quality standards. The specific problem is: Too many examples of unclear relevancy; not enough references; problematic mentions of header files and multiple declarations. (December 2013) |
In computer programming, a declaration is a language construct specifying identifier properties: it declares a word's (identifier's) meaning.[1] Declarations are most commonly used for functions, variables, constants, and classes, but can also be used for other entities such as enumerations and type definitions.[1] Beyond the name (the identifier itself) and the kind of entity (function, variable, etc.), declarations typically specify the data type (for variables and constants), or the type signature (for functions); types may also include dimensions, such as for arrays. A declaration is used to announce the existence of the entity to the compiler; this is important in those strongly typed languages that require functions, variables, and constants, and their types to be specified with a declaration before use, and is used in forward declaration.[2] The term "declaration" is frequently contrasted with the term "definition",[1] but meaning and usage varies significantly between languages; see below.
Declarations are particularly prominent in languages in the ALGOL tradition, including the BCPL family, most prominently C and C++, and also Pascal. Java uses the term "declaration", though Java does not require separate declarations and definitions.
Declaration vs. definition
[edit]One basic dichotomy is whether or not a declaration contains a definition: for example, whether a variable or constant declaration specifies its value, or only its type; and similarly whether a declaration of a function specifies the body (implementation) of the function, or only its type signature.[1] Not all languages make this distinction: in many languages, declarations always include a definition, and may be referred to as either "declarations" or "definitions", depending on the language.[a] However, these concepts are distinguished in languages that require declaration before use (for which forward declarations are used), and in languages where interface and implementation are separated: the interface contains declarations, the implementation contains definitions.[b]
In informal usage, a "declaration" refers only to a pure declaration (types only, no value or body), while a "definition" refers to a declaration that includes a value or body. However, in formal usage (in language specifications), "declaration" includes both of these senses, with finer distinctions by language: in C and C++, a declaration of a function that does not include a body is called a function prototype, while a declaration of a function that does include a body is called a "function definition". In Java declarations occur in two forms. For public methods they can be presented in interfaces as method signatures, which consist of the method names, input types and output type. A similar notation can be used in the definition of abstract methods, which do not contain a definition. The enclosing class can be instantiated, rather a new derived class, which provides the definition of the method, would need to be created in order to create an instance of the class. Starting with Java 8, the lambda expression was included in the language, which could be viewed as a function declaration.
Declarations and definitions
[edit]In the C-family of programming languages, declarations are often collected into header files, which are included in other source files that reference and use these declarations, but don't have access to the definition. The information in the header file provides the interface between code that uses the declaration and that which defines it, a form of information hiding. A declaration is often used in order to access functions or variables defined in different source files, or in a library. A mismatch between the definition type and the declaration type generates a compiler error.
For variables, definitions assign values to an area of memory that was reserved during the declaration phase. For functions, definitions supply the function body. While a variable or function may be declared many times, it is typically defined once (in C++, this is known as the One Definition Rule or ODR).
Dynamic languages such as JavaScript or Python generally allow functions to be redefined, that is, re-bound; a function is a variable much like any other, with a name and a value (the definition).
Here are some examples of declarations that are not definitions, in C:
extern char example1;
extern int example2;
void example3(void);
Here are some examples of declarations that are definitions, again in C:
char example1; /* Outside of a function definition it will be initialized to zero. */
int example2 = 5;
void example3(void) { /* definition between braces */ }
Undefined variables
[edit]In some programming languages, an implicit declaration is provided the first time such a variable is encountered at compile time. In other languages, such a usage is considered to be an error, which may result in a diagnostic message. Some languages have started out with the implicit declaration behavior, but as they matured they provided an option to disable it (e.g. Perl's "use strict
" or Visual Basic's "Option Explicit
").
See also
[edit]Notes
[edit]- ^ For example, Java uses "declaration" (class declaration, method declaration), while Python uses "definition" (class definition, function definition).[3]
- ^ This distinction is observed in Pascal "units" (modules), and in conventional C and C++ code organization, which has header files consisting largely of pure declarations, and source files consisting of definitions, though this is not always strictly observed, nor enforced by the language.
References
[edit]- ^ a b c d "A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that:
- for an object [variable or constant], causes storage to be reserved for that object;
- for a function, includes the function body;
- for an enumeration constant, is the (only) declaration of the identifier;
- for a typedef name, is the first (or only) declaration of the identifier."
- ^ Mike Banahan. "2.5. Declaration of variables". GBdirect. Retrieved 2011-06-08.
[A] declaration [...] introduces just the name and type of something but allocates no storage[...].
- ^ 7. Compound statements, The Python Language Reference
External links
[edit]- Declare vs Define in C and C++, Alex Allain
- 8.2. Declarations, Definitions and Accessibility, The C Book, GBdirect
- Declarations and Definitions (C++), MSDN
- "Declarations tell the compiler that a program element or name exists. Definitions specify what code or data the name describes."