Jump to content

Undefined variable

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by File Not Found (talk | contribs) at 03:43, 8 February 2006 (C example). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

An undefined variable in a computer program is a variable name that is called by the program but which has not been previously assigned a value by that program. This usually results in an undefined variable error message.

Examples

Each code example is followed by an error message.

Perl 5.8:

use strict;
my $y = $x;

Global symbol "$x" requires explicit package name at foo.pl line 2.
Execution of foo.pl aborted due to compilation errors.

Python 2.4:

 x = y

Traceback (most recent call last):
  File "foo.py", line 1, in ?
    x = y
NameError: name 'y' is not defined

JavaScript (Mozilla Firefox 1.0):

 y = x

 Error: x is not defined
 Source File: file:///c:/temp/foo.js

GNU CLISP 2.35:

(setf y x)

*** - EVAL: variable X has no value

Examples that behave differently

C does not have undefined variables. If a value is not assigned to a variable, the variable is called uninitialized, in which case it actually does contain a value, but the value is "garbage" (it could be any value). Leaving a variable uninitialized is not an error, but it is generally undesirable, and some compilers may trigger a warning at compile-time:

Microsoft C/C++ 6.0:

int main() {
  int y;
  int x = y;
  return 0;
}

foo.c(4) : warning C4700: local variable 'y' used without having been initialized

However, if a variable is undeclared, an error is generated at compile time:

GNU GCC 3.4:

int main() {
  int x = y;  // y undeclared
  return 0;
}

foo.c: In function `main':
foo.c:2: error: `y' 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.)

The closest thing in C to an undefined variable is a NULL pointer, which points to no value. Dereferencing a NULL pointer triggers a run-time error or crash:

GNU GCC 3.4:

  1. include <stdio.h>

int main() {

 int * x = NULL;
 int y = *x;
 return 0;

} (at run-time) Segmentation fault (core dumped)