Undefined variable
An undefined variable in the source code of a computer program is a variable that is accessed in the code but has not been previously declared by that code.
In some programming languages an implicit declaration is provided the first time such a variable is encountered at compile time or run time error. In other languages such a usage is considered to be a fatal error, resulting an 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>").
Examples
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).
CLISP (GNU CLISP 2.35): <source lang="lisp"> (setf y x) </source> <code> - EVAL: variable X has no value </code>
C (GNU GCC 3.4): <source lang="c"> int main() { int y = x; return 0; } </source> <code> foo.c: In function `main': foo.c:2: error: `x' undeclared (first use in this function) foo.c:2: error: (Each undeclared identifier is reported only once foo.c:2: error: for each function it appears in.) </code>
JavaScript (Mozilla Firefox 1.0):
<source lang="javascript"> y = x </source> <code> Error: x is not defined Source File: file:///c:/temp/foo.js </code>
ML (Standard ML of New Jersey v110.55):
<code> val y = x; </code> <code> stdIn:1.9 Error: unbound variable or constructor: x </code>
MUMPS
<code> Set Y=X </code> <code> <UNDEF> </code>
OCaml 3.08 <source lang="ocaml"> let y = x;; </source> <code> Unbound value x </code>
Perl 5.8: <source lang="perl"> my $y = $x; </source> <code> (no error) </code>
<source lang="perl"> use strict; my $y = $x; </source> <code> Global symbol "$x" requires explicit package name at foo.pl line 2. Execution of foo.pl aborted due to compilation errors. </code>
PHP 5: <source lang="php"> $y = $x; </source> <code> (no error) </code>
<source lang="php"> error_reporting(E_ALL); $y = $x; </source> <code> PHP Notice: Undefined variable: x in foo.php on line 3 </code>
Python 2.4: <source lang="python"> x = y </source> <code> Traceback (most recent call last): File "foo.py", line 1, in ? x = y NameError: name 'y' is not defined </code>
Ruby 1.8 <source lang="ruby"> y = x </source> <code> NameError: undefined local variable or method `x' for main:Object from (irb):1 </code>
VBScript (WSH 5.6) <source lang="vb"> Dim y y = x </source> <code> (no error) </code>
<source lang="vb"> Option Explicit
Dim y y = x </source> <code> (3, 1) Microsoft VBScript runtime error: Variable is undefined: 'x' </code>
|