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 declared by that 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 sufficiently serious that a diagnostic being issued and the compilation fails.
Some language definitions initially used the implicit declaration behavior and as they matured provided an option to disable it.
Examples
The following provides some examples of how various programming language implementations respond to undefined variables. Each code snippet is followed by an error message.[CLISP]
*** - EVAL: variable X has no value
C">C (programming language)">C
int main
foo.c: In function `main':
foo.c:2: error: `x' undeclared
foo.c:2: error:
[JavaScript]
A ReferenceError only happens if the same piece of executed code has a or a declaration later on, or if the code is executed in strict mode. In all other cases, the variable will have the special value."use strict";
let y = x;
let y = x;
let x; // causes error on line 1
ReferenceError: x is not defined
Source File: file:///c:/temp/foo.js
Lua">Lua (programming language)">Lua
y = x
nil
ML">Standard ML">ML (Standard ML of New Jersey)
val y = x;
stdIn:1.9 Error: unbound variable or constructor: x
[MUMPS]
Set Y=X[OCaml]
let y = x;;
Unbound value x
[Perl]
my $y = + 1; # defined-or operator
[PHP] 5
$y = $x;
$y="";
$x="";
error_reporting;
$y = $x;
PHP Notice: Undefined variable: x in foo.php on line 3
Python">Python (programming language)">Python
Python 3
x = y
Traceback :
File "
x = y
NameError: name 'y' is not defined
Python 2.4
>>> x = y
Traceback :
File "
NameError: name 'y' is not defined
[REXX]
signal on novalue
y = x
+++ Error 30 in line 2: Label not found
Ruby">Ruby (programming language)">Ruby
irb:001:0> y = x
NameError: undefined local variable or method `x' for main:Object
from :1
Tcl">Tcl (programming language)">Tcl
% set y $x
can't read "x": no such variable
[VBScript]
Dim y
y = x
Option Explicit
Dim y
y = x
Microsoft VBScript runtime error: Variable is undefined: 'x'