Undefined values: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 14: Line 14:
=={{header|ActionScript}}==
=={{header|ActionScript}}==
ActionScript has a special '''undefined''' value which applies to untyped variables and properties of dynamic classes which have not been initialized.
ActionScript has a special '''undefined''' value which applies to untyped variables and properties of dynamic classes which have not been initialized.
<lang actionscript>var foo; // untyped
<syntaxhighlight lang="actionscript">var foo; // untyped
var bar:*; // explicitly untyped
var bar:*; // explicitly untyped


Line 20: Line 20:


if (foo == undefined)
if (foo == undefined)
trace("foo is undefined"); // outputs "foo is undefined"</lang>
trace("foo is undefined"); // outputs "foo is undefined"</syntaxhighlight>


ActionScript also has a '''null''' value: see [[Null object#ActionScript]].
ActionScript also has a '''null''' value: see [[Null object#ActionScript]].
Line 31: Line 31:
This pragma is required to be applied to the whole partition, which would require recompilation of the run-time library. For this reason, the presented example uses another pragma Initialize_Scalars.
This pragma is required to be applied to the whole partition, which would require recompilation of the run-time library. For this reason, the presented example uses another pragma Initialize_Scalars.
This one has the effect similar to Normalize_Scalars, but is [[GNAT]]-specific:
This one has the effect similar to Normalize_Scalars, but is [[GNAT]]-specific:
<syntaxhighlight lang="ada">
<lang Ada>
pragma Initialize_Scalars;
pragma Initialize_Scalars;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
Line 55: Line 55:
end if;
end if;
end Invalid_Value;
end Invalid_Value;
</syntaxhighlight>
</lang>
Sample output:
Sample output:
<pre>
<pre>
Line 73: Line 73:


Note: Some implementations (eg [[ALGOL 68C]]) also have a procedure named ''undefined'' that is called to indicated that the behaviour at a particular point in a program is unexpected, undefined, or non-standard.
Note: Some implementations (eg [[ALGOL 68C]]) also have a procedure named ''undefined'' that is called to indicated that the behaviour at a particular point in a program is unexpected, undefined, or non-standard.
<lang algol68>MODE R = REF BOOL;
<syntaxhighlight lang="algol68">MODE R = REF BOOL;
R r := NIL;
R r := NIL;


Line 88: Line 88:
(VOID):print(("u is EMPTY", new line))
(VOID):print(("u is EMPTY", new line))
OUT print(("u isnt EMPTY", new line))
OUT print(("u isnt EMPTY", new line))
ESAC</lang>
ESAC</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 96: Line 96:


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>undef: null
<syntaxhighlight lang="rebol">undef: null


print undef</lang>
print undef</syntaxhighlight>


{{out}}
{{out}}
Line 109: Line 109:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
A scalar variable (numeric or string) cannot have an 'undefined' value; if an attempt is made to read a variable which has never been defined a 'No such variable' error results. By trapping errors this condition can be detected:
A scalar variable (numeric or string) cannot have an 'undefined' value; if an attempt is made to read a variable which has never been defined a 'No such variable' error results. By trapping errors this condition can be detected:
<lang bbcbasic> ok% = TRUE
<syntaxhighlight lang="bbcbasic"> ok% = TRUE
ON ERROR LOCAL IF ERR<>26 REPORT : END ELSE ok% = FALSE
ON ERROR LOCAL IF ERR<>26 REPORT : END ELSE ok% = FALSE
IF ok% THEN
IF ok% THEN
Line 116: Line 116:
PRINT "Not defined"
PRINT "Not defined"
ENDIF
ENDIF
RESTORE ERROR</lang>
RESTORE ERROR</syntaxhighlight>


{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
Arrays and structures however '''can''' have an undefined state; for example after having been declared as LOCAL or PRIVATE but before being defined using DIM. This condition can be detected and manipulated:
Arrays and structures however '''can''' have an undefined state; for example after having been declared as LOCAL or PRIVATE but before being defined using DIM. This condition can be detected and manipulated:
<lang bbcbasic> PROCtest
<syntaxhighlight lang="bbcbasic"> PROCtest
END
END
Line 130: Line 130:
!^array() = 0 : REM Set array to undefined state
!^array() = 0 : REM Set array to undefined state
ENDPROC</lang>
ENDPROC</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
Line 139: Line 139:
C programs can also read garbage values from uninitialized memory. There is no way to test for these garbage values, because they might equal anything.
C programs can also read garbage values from uninitialized memory. There is no way to test for these garbage values, because they might equal anything.


<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>


Line 154: Line 154:
printf("*junkp: %d\n", *junkp);
printf("*junkp: %d\n", *junkp);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
In C# it's important to see the difference between reference and value types. For reference types (class instances) there is <code>null</code> as a general undefined reference.
In C# it's important to see the difference between reference and value types. For reference types (class instances) there is <code>null</code> as a general undefined reference.
<lang csharp>string foo = null;</lang>
<syntaxhighlight lang="csharp">string foo = null;</syntaxhighlight>
Dereferencing a null reference will throw a <code>NullReferenceException</code>.
Dereferencing a null reference will throw a <code>NullReferenceException</code>.


This can't be used normally for value types (<code>int</code>, <code>double</code>, <code>DateTime</code>, etc.) since they are no ''references,'' so the following is a compiler error:
This can't be used normally for value types (<code>int</code>, <code>double</code>, <code>DateTime</code>, etc.) since they are no ''references,'' so the following is a compiler error:
<lang csharp>int i = null;</lang>
<syntaxhighlight lang="csharp">int i = null;</syntaxhighlight>
With .NET 2.0 there is an additional <code>Nullable<T></code> structure which enables those semantics for value types as well:
With .NET 2.0 there is an additional <code>Nullable<T></code> structure which enables those semantics for value types as well:
<lang csharp>int? answer = null;
<syntaxhighlight lang="csharp">int? answer = null;
if (answer == null) {
if (answer == null) {
answer = 42;
answer = 42;
}</lang>
}</syntaxhighlight>
There is a bit syntactic sugar involved here. The <code>?</code> after the type name signals the compiler that it's a ''nullable'' type. This only works for value types since reference types are nullable due to their very nature.
There is a bit syntactic sugar involved here. The <code>?</code> after the type name signals the compiler that it's a ''nullable'' type. This only works for value types since reference types are nullable due to their very nature.


But since value types still can't actually ''have'' a <code>null</code> value this gets converted into the following code by the compiler:
But since value types still can't actually ''have'' a <code>null</code> value this gets converted into the following code by the compiler:
<lang csharp>Nullable<int> answer = new Nullable<int>();
<syntaxhighlight lang="csharp">Nullable<int> answer = new Nullable<int>();
if (!answer.HasValue) {
if (!answer.HasValue) {
answer = new Nullable<int>(42);
answer = new Nullable<int>(42);
}</lang>
}</syntaxhighlight>
So it's a little compiler magic but in the end works just as one would expect.
So it's a little compiler magic but in the end works just as one would expect.


Line 184: Line 184:
the behavior is undefined, the compiler can do whatever it wants. Most compilers will give a warning.
the behavior is undefined, the compiler can do whatever it wants. Most compilers will give a warning.


<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>


int main()
int main()
Line 198: Line 198:
std::cout << "not 42";
std::cout << "not 42";
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 210: Line 210:
In Lisp, there are three possibilities with regard to a dynamic variable. It may exist, and have a value. It may exist, but not have a value. Or it may not exist at all. These situations can be probed with certain functions that take a symbol as an argument:
In Lisp, there are three possibilities with regard to a dynamic variable. It may exist, and have a value. It may exist, but not have a value. Or it may not exist at all. These situations can be probed with certain functions that take a symbol as an argument:


<lang lisp>
<syntaxhighlight lang="lisp">
;; assumption: none of these variables initially exist
;; assumption: none of these variables initially exist


Line 220: Line 220:
(boundp '*y*) -> T
(boundp '*y*) -> T


(special-variable-p '*z*) -> NIL ;; *z* does not name a special variable</lang>
(special-variable-p '*z*) -> NIL ;; *z* does not name a special variable</syntaxhighlight>


Furthermore, a variable which is bound can be made unbound:
Furthermore, a variable which is bound can be made unbound:


<lang lisp>
<syntaxhighlight lang="lisp">
(makunbound '*y*) ;; *y* no longer has a value; it is erroneous to evaluate *y*
(makunbound '*y*) ;; *y* no longer has a value; it is erroneous to evaluate *y*


(setf *y* 43) ;; *y* is bound again.</lang>
(setf *y* 43) ;; *y* is bound again.</syntaxhighlight>


By contrast, lexical variables never lack a binding. Without an initializer, they are initialized to nil.
By contrast, lexical variables never lack a binding. Without an initializer, they are initialized to nil.
The same goes for local re-binding of special variables:
The same goes for local re-binding of special variables:


<lang lisp>
<syntaxhighlight lang="lisp">
(defvar *dyn*) ;; special, no binding
(defvar *dyn*) ;; special, no binding


Line 239: Line 239:
(list (boundp '*dyn*) *dyn* (boundp 'lex) lex)) -> (T NIL NIL NIL)
(list (boundp '*dyn*) *dyn* (boundp 'lex) lex)) -> (T NIL NIL NIL)


(boundp '*global*) -> NIL</lang>
(boundp '*global*) -> NIL</syntaxhighlight>


Here we can see that inside the scope of the let, the special variable has a binding (to the value <code>NIL</code>) and so <code>(boundp '*dyn*)</code> yields <code>T</code>. But <code>boundp</code> does not "see" the lexical variable <code>lex</code>; it reports that <code>lex</code> is unbound. Local binding constructs never leave a variable without a value, be it dynamic or lexical: both <code>*dyn*</code> and <code>lex</code> evaluate to NIL, but using very different mechanisms.
Here we can see that inside the scope of the let, the special variable has a binding (to the value <code>NIL</code>) and so <code>(boundp '*dyn*)</code> yields <code>T</code>. But <code>boundp</code> does not "see" the lexical variable <code>lex</code>; it reports that <code>lex</code> is unbound. Local binding constructs never leave a variable without a value, be it dynamic or lexical: both <code>*dyn*</code> and <code>lex</code> evaluate to NIL, but using very different mechanisms.
Line 245: Line 245:
=={{header|D}}==
=={{header|D}}==
In D variables are initialized either with an explicit Initializer or are set to the default value for the type of the variable. If the Initializer is void, however, the variable is not initialized. If its value is used before it is set, undefined program behavior will result. "void" initializers can be used to avoid the overhead of default initialization in performance critical code.
In D variables are initialized either with an explicit Initializer or are set to the default value for the type of the variable. If the Initializer is void, however, the variable is not initialized. If its value is used before it is set, undefined program behavior will result. "void" initializers can be used to avoid the overhead of default initialization in performance critical code.
<lang d>void main() {
<syntaxhighlight lang="d">void main() {
// Initialized:
// Initialized:
int a = 5;
int a = 5;
Line 263: Line 263:
double[] bbb = void;
double[] bbb = void;
int[3] eee = void;
int[3] eee = void;
}</lang>
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
Line 269: Line 269:


For Referenced data types like pointers, classes and interfaces a reference can be explicitely set to undefined by assigning the NIL value for it. No memory management like garbage collection (except for interfaces) is done.
For Referenced data types like pointers, classes and interfaces a reference can be explicitely set to undefined by assigning the NIL value for it. No memory management like garbage collection (except for interfaces) is done.
<lang delphi>var
<syntaxhighlight lang="delphi">var
P: PInteger;
P: PInteger;
begin
begin
Line 281: Line 281:
Dispose(P); //Release memory allocated by New
Dispose(P); //Release memory allocated by New
end;
end;
end;</lang>
end;</syntaxhighlight>


If P was a Class only the Assigned function would be available; in addition Dispose would have to be replaced by FreeAndNil or calling the .Free method of the instance. For Interfaces no such last call would be necessary as simple removal of the reference would be sufficient to trigger the Garbage Collector.
If P was a Class only the Assigned function would be available; in addition Dispose would have to be replaced by FreeAndNil or calling the .Free method of the instance. For Interfaces no such last call would be necessary as simple removal of the reference would be sufficient to trigger the Garbage Collector.
Line 287: Line 287:
=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
There is no undefined value in Déjà Vu. Instead, trying to access an undefined variable raises an exception.
There is no undefined value in Déjà Vu. Instead, trying to access an undefined variable raises an exception.
<lang dejavu>try:
<syntaxhighlight lang="dejavu">try:
bogus
bogus
catch name-error:
catch name-error:
!print "There is *no* :bogus in the current context"
!print "There is *no* :bogus in the current context"
return
return
!print "You won't see this."</lang>
!print "You won't see this."</syntaxhighlight>
If you need to declare a local variable, but don't have a value for it yet, there is the standard function <code>undef</code>, which raises an exception when called but is an actual value that can be passed around and assigned to names.
If you need to declare a local variable, but don't have a value for it yet, there is the standard function <code>undef</code>, which raises an exception when called but is an actual value that can be passed around and assigned to names.


Line 305: Line 305:
Each variable's behavior is defined by a <em>slot</em> object with <code>get</code> and <code>put</code> methods. If the slot throws when invoked, then a program may contain a reference to that variable, but not actually access it. A notable way for the slot to throw is for the slot to itself be a broken reference. This may occur when slots are being passed around as part of metaprogramming or export/import; it is also used in certain control structures. For example:
Each variable's behavior is defined by a <em>slot</em> object with <code>get</code> and <code>put</code> methods. If the slot throws when invoked, then a program may contain a reference to that variable, but not actually access it. A notable way for the slot to throw is for the slot to itself be a broken reference. This may occur when slots are being passed around as part of metaprogramming or export/import; it is also used in certain control structures. For example:


<lang e>if (foo == bar || (def baz := lookup(foo)) != null) {
<syntaxhighlight lang="e">if (foo == bar || (def baz := lookup(foo)) != null) {
...
...
}</lang>
}</syntaxhighlight>


The slot for <var>baz</var> is broken if the left side of the <code>||</code> was true and the right side was therefore not evaluated.
The slot for <var>baz</var> is broken if the left side of the <code>||</code> was true and the right side was therefore not evaluated.
Line 315: Line 315:
=={{header|Erlang}}==
=={{header|Erlang}}==
In Erlang a variable is created by assigning to it, so all variables have a value. To get undefined values you have to use a record. The default value of a record member is undefined.
In Erlang a variable is created by assigning to it, so all variables have a value. To get undefined values you have to use a record. The default value of a record member is undefined.
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( undefined_values ).
-module( undefined_values ).


Line 326: Line 326:
io:fwrite( "Record member_1 ~p, member_2 ~p~n", [Record#a_record.member_1, Record#a_record.member_2] ),
io:fwrite( "Record member_1 ~p, member_2 ~p~n", [Record#a_record.member_1, Record#a_record.member_2] ),
io:fwrite( "Member_2 is undefined ~p~n", [Record#a_record.member_2 =:= undefined] ).
io:fwrite( "Member_2 is undefined ~p~n", [Record#a_record.member_2 =:= undefined] ).
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 340: Line 340:
=={{header|Factor}}==
=={{header|Factor}}==
Factor does not have undefined values. Most values used in Factor live on the data stack. They are not named, so it is not possible for them to be undefined:
Factor does not have undefined values. Most values used in Factor live on the data stack. They are not named, so it is not possible for them to be undefined:
<lang factor>42 . ! 42</lang>
<syntaxhighlight lang="factor">42 . ! 42</syntaxhighlight>


Tuple slots are always initialized with <code>f</code> or other values like <code>0</code> when the slot has been class-restricted:
Tuple slots are always initialized with <code>f</code> or other values like <code>0</code> when the slot has been class-restricted:
<lang factor>TUPLE: foo bar ;
<syntaxhighlight lang="factor">TUPLE: foo bar ;
foo new bar>> . ! f
foo new bar>> . ! f


TUPLE: my-tuple { n integer } ;
TUPLE: my-tuple { n integer } ;
my-tuple new n>> . ! 0</lang>
my-tuple new n>> . ! 0</syntaxhighlight>


Dynamic variables (and indeed all words) are initialized to <code>f</code>:
Dynamic variables (and indeed all words) are initialized to <code>f</code>:
<lang factor>SYMBOL: n
<syntaxhighlight lang="factor">SYMBOL: n
n get . ! f
n get . ! f


\ + get . ! f</lang>
\ + get . ! f</syntaxhighlight>


Finally, Factor does not allow lexical variables to be declared without initialization:
Finally, Factor does not allow lexical variables to be declared without initialization:


<lang factor>[let
<syntaxhighlight lang="factor">[let
2 :> n ! There is no other way!
2 :> n ! There is no other way!
0 1 :> ( a b )
0 1 :> ( a b )
]</lang>
]</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 368: Line 368:


More modern Fortrans recognise the NaN state of floating-point variables on computers whose floating-point arithmetic follows the IEEE standard, via the logical function
More modern Fortrans recognise the NaN state of floating-point variables on computers whose floating-point arithmetic follows the IEEE standard, via the logical function
<lang Fortran>IsNaN(x)</lang>
<syntaxhighlight lang="fortran">IsNaN(x)</syntaxhighlight>
This is the only safe way to detect them as tests to detect the special behaviour of NaN states such as ''if x = x then...else aha!;'' might be optimised away by the compiler, and other tests may behave oddly. For instance x ¬= 0 might be compiled as ¬(x = 0) and the special NaN behaviour will not be as expected. Such NaN values can come via READ statements, because "NaN" is a recognised numerical input option, and could be used instead of "999" in a F3.0 data field, etc. Or, your system's input processing might recognise "?" or other special indicators and so on.
This is the only safe way to detect them as tests to detect the special behaviour of NaN states such as ''if x = x then...else aha!;'' might be optimised away by the compiler, and other tests may behave oddly. For instance x ¬= 0 might be compiled as ¬(x = 0) and the special NaN behaviour will not be as expected. Such NaN values can come via READ statements, because "NaN" is a recognised numerical input option, and could be used instead of "999" in a F3.0 data field, etc. Or, your system's input processing might recognise "?" or other special indicators and so on.


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
In FreeBASIC all variables are given a default value (zero for numbers, false for boolean and empty for strings) when they are declared unless they are assigned a different value at that time or are specifically left uninitialized (using the 'Any' keyword). If the latter are used before they have been initialized, then they will contain a 'garbage' value i.e. whatever value happens to be in the associated memory:
In FreeBASIC all variables are given a default value (zero for numbers, false for boolean and empty for strings) when they are declared unless they are assigned a different value at that time or are specifically left uninitialized (using the 'Any' keyword). If the latter are used before they have been initialized, then they will contain a 'garbage' value i.e. whatever value happens to be in the associated memory:
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Dim i As Integer '' initialized to 0 by default
Dim i As Integer '' initialized to 0 by default
Line 380: Line 380:


Print i, j, k
Print i, j, k
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 389: Line 389:


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap>IsBound(a);
<syntaxhighlight lang="gap">IsBound(a);
# true
# true


Line 395: Line 395:


IsBound(a);
IsBound(a);
# false</lang>
# false</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
Line 405: Line 405:
# Successful (non panicking) use of initialized objects.
# Successful (non panicking) use of initialized objects.
# One more quirky little feature involving a type switch on a nil interface.
# One more quirky little feature involving a type switch on a nil interface.
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 501: Line 501:
close(c)
close(c)
fmt.Println("channel closed")
fmt.Println("channel closed")
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 526: Line 526:
In Haskell, there is a semantic concept called [http://www.haskell.org/haskellwiki/Bottom "bottom"], which is a computation that never terminates or runs into an error. So <code>undefined</code> is not a proper value at all; it is a bottom that causes an exception when evaluated. For example,
In Haskell, there is a semantic concept called [http://www.haskell.org/haskellwiki/Bottom "bottom"], which is a computation that never terminates or runs into an error. So <code>undefined</code> is not a proper value at all; it is a bottom that causes an exception when evaluated. For example,


<lang haskell>main = print $ "Incoming error--" ++ undefined
<syntaxhighlight lang="haskell">main = print $ "Incoming error--" ++ undefined
-- When run in GHC:
-- When run in GHC:
-- "Incoming error--*** Exception: Prelude.undefined</lang>
-- "Incoming error--*** Exception: Prelude.undefined</syntaxhighlight>


This isn't quite as dangerous as it sounds because of Haskell's laziness. For example, this program:
This isn't quite as dangerous as it sounds because of Haskell's laziness. For example, this program:


<lang haskell>main = print $ length [undefined, undefined, 1 `div` 0]</lang>
<syntaxhighlight lang="haskell">main = print $ length [undefined, undefined, 1 `div` 0]</syntaxhighlight>


prints <code>3</code>, since <code>length</code> doesn't need to evaluate any of the elements of its input.
prints <code>3</code>, since <code>length</code> doesn't need to evaluate any of the elements of its input.
Line 538: Line 538:
In practice, one uses <code>undefined</code> less often than <code>error</code>, which behaves exactly the same except that it lets you choose the error message. So if you say
In practice, one uses <code>undefined</code> less often than <code>error</code>, which behaves exactly the same except that it lets you choose the error message. So if you say


<lang haskell>resurrect 0 = error "I'm out of orange smoke!"</lang>
<syntaxhighlight lang="haskell">resurrect 0 = error "I'm out of orange smoke!"</syntaxhighlight>


then if you make the mistake of writing your program such that it at some point requires the value of <code>resurrect 0</code>, you'll get the error message "I'm out of orange smoke!". <code>undefined</code> may be defined in the same way:
then if you make the mistake of writing your program such that it at some point requires the value of <code>resurrect 0</code>, you'll get the error message "I'm out of orange smoke!". <code>undefined</code> may be defined in the same way:


<lang haskell>undefined :: a
<syntaxhighlight lang="haskell">undefined :: a
undefined = error "Prelude.undefined"</lang>
undefined = error "Prelude.undefined"</syntaxhighlight>


Since <code>undefined</code> causes an exception, the usual exception handling mechanism can be used to catch it:
Since <code>undefined</code> causes an exception, the usual exception handling mechanism can be used to catch it:


<lang haskell>import Control.Exception (catch, evaluate, ErrorCall)
<syntaxhighlight lang="haskell">import Control.Exception (catch, evaluate, ErrorCall)
import System.IO.Unsafe (unsafePerformIO)
import System.IO.Unsafe (unsafePerformIO)
import Prelude hiding (catch)
import Prelude hiding (catch)
Line 562: Line 562:
main = do
main = do
print $ safeHead ([] :: String)
print $ safeHead ([] :: String)
print $ safeHead ["str"]</lang>
print $ safeHead ["str"]</syntaxhighlight>


== Icon and Unicon ==
== Icon and Unicon ==
Line 570: Line 570:


==={{header|Unicon}}===
==={{header|Unicon}}===
<lang Unicon>global G1
<syntaxhighlight lang="unicon">global G1


procedure main(arglist)
procedure main(arglist)
Line 584: Line 584:
write((localnames|paramnames|staticnames|globalnames)(&current,0)) # ... visible in the current co-expression at this calling level (0)
write((localnames|paramnames|staticnames|globalnames)(&current,0)) # ... visible in the current co-expression at this calling level (0)
return
return
end</lang>
end</syntaxhighlight>


The output looks like:
The output looks like:
Line 603: Line 603:
J does not have a concept of an "undefined value" as such, but J does allow treatment of undefined names. The verb <code>nc</code> finds the (syntactic) class of a name. This result is negative one for names which have not been defined.
J does not have a concept of an "undefined value" as such, but J does allow treatment of undefined names. The verb <code>nc</code> finds the (syntactic) class of a name. This result is negative one for names which have not been defined.


<syntaxhighlight lang="j">
<lang J>
foo=: 3
foo=: 3
nc;:'foo bar'
nc;:'foo bar'
0 _1</lang>
0 _1</syntaxhighlight>


From this we can infer that <code>foo</code> has a definition (and its definition is a noun, since 0 is the syntactic [http://www.jsoftware.com/help/dictionary/dx004.htm name class] for nouns), and we can also infer that <code>bar</code> does not have a definition.
From this we can infer that <code>foo</code> has a definition (and its definition is a noun, since 0 is the syntactic [http://www.jsoftware.com/help/dictionary/dx004.htm name class] for nouns), and we can also infer that <code>bar</code> does not have a definition.
Line 612: Line 612:
This task also asked that we ''identify and exercise .. mechanisms for ... manipulating a variable's value's status as being undefined''. So: a name can be made to be undefined using the verb <code>erase</code>. The undefined status can be removed by assigning a value to the name.
This task also asked that we ''identify and exercise .. mechanisms for ... manipulating a variable's value's status as being undefined''. So: a name can be made to be undefined using the verb <code>erase</code>. The undefined status can be removed by assigning a value to the name.


<syntaxhighlight lang="j">
<lang J>
erase;:'foo bar'
erase;:'foo bar'
1 1
1 1
Line 619: Line 619:
bar=:99
bar=:99
nc;:'foo bar'
nc;:'foo bar'
_1 0</lang>
_1 0</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
Line 625: Line 625:


Java has a special null type, the type of the expression <code>null</code>, that can be cast to any reference type; in practice the null type can be ignored and <code>null</code> can be treated as a special literal that can be of any reference type. When a reference variable has the special value <code>null</code> it refers to no object, meaning that it is undefined.
Java has a special null type, the type of the expression <code>null</code>, that can be cast to any reference type; in practice the null type can be ignored and <code>null</code> can be treated as a special literal that can be of any reference type. When a reference variable has the special value <code>null</code> it refers to no object, meaning that it is undefined.
<lang java>String string = null; // the variable string is undefined
<syntaxhighlight lang="java">String string = null; // the variable string is undefined
System.out.println(string); //prints "null" to std out
System.out.println(string); //prints "null" to std out
System.out.println(string.length()); // dereferencing null throws java.lang.NullPointerException</lang>
System.out.println(string.length()); // dereferencing null throws java.lang.NullPointerException</syntaxhighlight>


Variables of primitive types cannot be assigned the special value <code>null</code>, but there are wrapper classes corresponding to the primitive types (eg. <code>Boolean</code>, <code>Integer</code>, <code>Long</code>, <code>Double</code>, &c), that can be used instead of the corresponding primitive; since they can have the special value <code>null</code> it can be used to identify the variable as undefined.
Variables of primitive types cannot be assigned the special value <code>null</code>, but there are wrapper classes corresponding to the primitive types (eg. <code>Boolean</code>, <code>Integer</code>, <code>Long</code>, <code>Double</code>, &c), that can be used instead of the corresponding primitive; since they can have the special value <code>null</code> it can be used to identify the variable as undefined.
<lang java>int i = null; // compilation error: incompatible types, required: int, found: <nulltype>
<syntaxhighlight lang="java">int i = null; // compilation error: incompatible types, required: int, found: <nulltype>
if (i == null) { // compilation error: incomparable types: int and <nulltype>
if (i == null) { // compilation error: incomparable types: int and <nulltype>
i = 1;
i = 1;
}</lang>
}</syntaxhighlight>
But this piece of code can be made valid by replacing <code>int</code> with <code>Integer</code>, and thanks to the automatic conversion between primitive types and their wrapper classes (called autoboxing) the only change required is in the declaration of the variable:
But this piece of code can be made valid by replacing <code>int</code> with <code>Integer</code>, and thanks to the automatic conversion between primitive types and their wrapper classes (called autoboxing) the only change required is in the declaration of the variable:
<lang java>Integer i = null; // variable i is undefined
<syntaxhighlight lang="java">Integer i = null; // variable i is undefined
if (i == null) {
if (i == null) {
i = 1;
i = 1;
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
In Javascript undefined is a property of the global object, i.e. it is a variable in global scope. The initial value of undefined is the primitive value undefined. The problem with using undefined is that undefined is mutable. Instead we can use typeof to check if a value is undefined.
In Javascript undefined is a property of the global object, i.e. it is a variable in global scope. The initial value of undefined is the primitive value undefined. The problem with using undefined is that undefined is mutable. Instead we can use typeof to check if a value is undefined.
<lang javascript>var a;
<syntaxhighlight lang="javascript">var a;


typeof(a) === "undefined";
typeof(a) === "undefined";
Line 654: Line 654:
obj.c === 42;
obj.c === 42;
delete obj.c;
delete obj.c;
typeof(obj.c) === "undefined";</lang>
typeof(obj.c) === "undefined";</syntaxhighlight>


We can also use the prefix keyword void, it always returns undefined. But this will throw a error if the variable has not been defined.
We can also use the prefix keyword void, it always returns undefined. But this will throw a error if the variable has not been defined.
<lang javascript>var a;
<syntaxhighlight lang="javascript">var a;
a === void 0; // true
a === void 0; // true
b === void 0; // throws a ReferenceError</lang>
b === void 0; // throws a ReferenceError</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
Given a JSON object, o, and a key, k, that is not present in that object, then o[k] evaluates to null, e.g.
Given a JSON object, o, and a key, k, that is not present in that object, then o[k] evaluates to null, e.g.
<lang jq>{}["key"] #=> null</lang>
<syntaxhighlight lang="jq">{}["key"] #=> null</syntaxhighlight>


In an important sense, therefore, null in jq represents an undefined value. However, it should be noted that in jq, 1/0 does not yield null:
In an important sense, therefore, null in jq represents an undefined value. However, it should be noted that in jq, 1/0 does not yield null:
<lang jq>1/0 == null #=>false</lang>
<syntaxhighlight lang="jq">1/0 == null #=>false</syntaxhighlight>


It should also be noted that in jq, null can combine with other values to form non-null values. Specifically, for any JSON entity, e,
It should also be noted that in jq, null can combine with other values to form non-null values. Specifically, for any JSON entity, e,
Line 672: Line 672:


For example, suppose it is agreed that the "sum" of the elements of an empty array should be null. Then one can simply write:
For example, suppose it is agreed that the "sum" of the elements of an empty array should be null. Then one can simply write:
<lang jq>def sum: reduce .[] as $x (null; . + $x);</lang>
<syntaxhighlight lang="jq">def sum: reduce .[] as $x (null; . + $x);</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
Line 685: Line 685:
</code>
</code>
2. For variables that are defined for the Julia program but have undefined values, there are two types of undefined value in Julia (version > 0.7): <code> nothing </code> and <code> missing </code>. "nothing" and "missing" are typed constants used by convention to refer to either (with <code> nothing </code>) an absent result, such as a search with nothing found, or in the case of <code> missing, </code> a data location containing a missing value, such as a data table with missing values. <code>nothing</code> generally produces an error if any calculations incorporate it, but <code>missing</code> can be propagated along a calculation:
2. For variables that are defined for the Julia program but have undefined values, there are two types of undefined value in Julia (version > 0.7): <code> nothing </code> and <code> missing </code>. "nothing" and "missing" are typed constants used by convention to refer to either (with <code> nothing </code>) an absent result, such as a search with nothing found, or in the case of <code> missing, </code> a data location containing a missing value, such as a data table with missing values. <code>nothing</code> generally produces an error if any calculations incorporate it, but <code>missing</code> can be propagated along a calculation:
<lang julia>
<syntaxhighlight lang="julia">
julia> arr = [1, 2, nothing, 3]
julia> arr = [1, 2, nothing, 3]
4-element Array{Union{Nothing, Int64},1}:
4-element Array{Union{Nothing, Int64},1}:
Line 714: Line 714:
missing
missing
8
8
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
Line 724: Line 724:


Here are some simple examples illustrating these points:
Here are some simple examples illustrating these points:
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


class SomeClass
class SomeClass
Line 761: Line 761:
println(e)
println(e)
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 771: Line 771:
=={{header|Lingo}}==
=={{header|Lingo}}==
In Lingo an undefined variable has the value <Void>. If a variable is <Void> (i.e. undefined) can be checked by comparing it with the constant VOID, or by using the function voidP():
In Lingo an undefined variable has the value <Void>. If a variable is <Void> (i.e. undefined) can be checked by comparing it with the constant VOID, or by using the function voidP():
<lang lingo>put var
<syntaxhighlight lang="lingo">put var
-- <Void>
-- <Void>
put var=VOID
put var=VOID
Line 779: Line 779:
var = 23
var = 23
put voidP(var)
put voidP(var)
-- 0</lang>
-- 0</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
Line 786: Line 786:
UCB Logo has separate namespaces for procedures and variables ("names"). There is no distinction between a proc/name with no value and an undefined proc/name.
UCB Logo has separate namespaces for procedures and variables ("names"). There is no distinction between a proc/name with no value and an undefined proc/name.


<lang logo>; procedures
<syntaxhighlight lang="logo">; procedures
to square :x
to square :x
output :x * :x
output :x * :x
Line 804: Line 804:
ern "n
ern "n
show name? "n ; false
show name? "n ; false
show :n ; n has no value</lang>
show :n ; n has no value</syntaxhighlight>


=={{header|LOLCODE}}==
=={{header|LOLCODE}}==
LOLCODE's nil value is called <tt>NOOB</tt>, to which all uninitialized variables evaluate, and which is distinct from <tt>FAIL</tt>, the false value.
LOLCODE's nil value is called <tt>NOOB</tt>, to which all uninitialized variables evaluate, and which is distinct from <tt>FAIL</tt>, the false value.
<lang LOLCODE>HAI 1.3
<syntaxhighlight lang="lolcode">HAI 1.3


I HAS A foo BTW, INISHULIZD TO NOOB
I HAS A foo BTW, INISHULIZD TO NOOB
Line 825: Line 825:
OIC
OIC


KTHXBYE</lang>
KTHXBYE</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>print( a )
<syntaxhighlight lang="lua">print( a )


local b
local b
Line 836: Line 836:
b = 5
b = 5
end
end
print( b )</lang>
print( b )</syntaxhighlight>
Output:
Output:
<pre>nil
<pre>nil
Line 844: Line 844:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Mathematica is a symbolic mathematical software. Variables without given values are treated as symbols.
Mathematica is a symbolic mathematical software. Variables without given values are treated as symbols.
<syntaxhighlight lang="mathematica">a
<lang Mathematica>a
-> a
-> a
a + a
a + a
Line 853: Line 853:
-> 5
-> 5
ValueQ[a]
ValueQ[a]
-> True</lang>
-> True</syntaxhighlight>
Mathematica also has a build-in symbol "Undefined", representing a quantity with no defined value.
Mathematica also has a build-in symbol "Undefined", representing a quantity with no defined value.
<lang Mathematica>ConditionalExpression[a, False]
<syntaxhighlight lang="mathematica">ConditionalExpression[a, False]
->Undefined</lang>
->Undefined</syntaxhighlight>
Mathematical expressions containing Undefined evaluate to Undefined:
Mathematical expressions containing Undefined evaluate to Undefined:
<lang Mathematica>Sin[Undefined]
<syntaxhighlight lang="mathematica">Sin[Undefined]
-> Undefined </lang>
-> Undefined </syntaxhighlight>
Of course you can assign Undefined to be the value of a variable. Here "Undefined" is itself a value.
Of course you can assign Undefined to be the value of a variable. Here "Undefined" is itself a value.
<lang Mathematica>a = Undefined
<syntaxhighlight lang="mathematica">a = Undefined
-> Undefined
-> Undefined
a
a
-> Undefined
-> Undefined
ValueQ[a]
ValueQ[a]
-> True</lang>
-> True</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==


If a variable is generated without defing a value, e.g. with
If a variable is generated without defing a value, e.g. with
<lang Matlab> global var; </lang>
<syntaxhighlight lang="matlab"> global var; </syntaxhighlight>
the variable is empty, and can be tested with
the variable is empty, and can be tested with
<lang Matlab> isempty(var) </lang>
<syntaxhighlight lang="matlab"> isempty(var) </syntaxhighlight>


For numerical values (e.g. vectors or arrays) with a predefined size, often not-a-numbers (NaN's) user used to indicate missing values,
For numerical values (e.g. vectors or arrays) with a predefined size, often not-a-numbers (NaN's) user used to indicate missing values,
<lang Matlab> var = [1, 2, NaN, 0/0, inf-inf, 5] </lang>
<syntaxhighlight lang="matlab"> var = [1, 2, NaN, 0/0, inf-inf, 5] </syntaxhighlight>
These can be tested with:
These can be tested with:
<lang Matlab> isnan(var) </lang>
<syntaxhighlight lang="matlab"> isnan(var) </syntaxhighlight>


<pre>
<pre>
Line 888: Line 888:
=={{header|MUMPS}}==
=={{header|MUMPS}}==
<p>MUMPS does have variables with undefined values, but referencing them usually causes an error. To test for whether a value is undefined use the $Data function. If you are trying to read a value that may be undefined, use $Get as a wrapper. Note that an alternate form of $Get can return a specified value, which must be defined.</p>
<p>MUMPS does have variables with undefined values, but referencing them usually causes an error. To test for whether a value is undefined use the $Data function. If you are trying to read a value that may be undefined, use $Get as a wrapper. Note that an alternate form of $Get can return a specified value, which must be defined.</p>
<lang MUMPS> IF $DATA(SOMEVAR)=0 DO UNDEF ; A result of 0 means the value is undefined
<syntaxhighlight lang="mumps"> IF $DATA(SOMEVAR)=0 DO UNDEF ; A result of 0 means the value is undefined
SET LOCAL=$GET(^PATIENT(RECORDNUM,0)) ;If there isn't a defined item at that location, a null string is returned</lang>
SET LOCAL=$GET(^PATIENT(RECORDNUM,0)) ;If there isn't a defined item at that location, a null string is returned</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
Line 895: Line 895:


So, there are no undefined values except if the user explicitly specified that the variable must not be initialized. This may be useful for instance for a big array which will be initialized later on. To avoid the implicit initialization, we use the pragma <code>{.noInit.}</code>. For instance:
So, there are no undefined values except if the user explicitly specified that the variable must not be initialized. This may be useful for instance for a big array which will be initialized later on. To avoid the implicit initialization, we use the pragma <code>{.noInit.}</code>. For instance:
<lang Nim>var a {.noInit.}: array[1_000_000, int]
<syntaxhighlight lang="nim">var a {.noInit.}: array[1_000_000, int]


# For a proc, {.noInit.} means that the result is not initialized.
# For a proc, {.noInit.} means that the result is not initialized.
proc p(): array[1000, int] {.noInit.} =
proc p(): array[1000, int] {.noInit.} =
for i in 0..999: result[i] = i</lang>
for i in 0..999: result[i] = i</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==


<lang ocaml>(* There is no undefined value in OCaml,
<syntaxhighlight lang="ocaml">(* There is no undefined value in OCaml,
but if you really need this you can use the built-in "option" type.
but if you really need this you can use the built-in "option" type.
It is defined like this: type 'a option = None | Some of 'a *)
It is defined like this: type 'a option = None | Some of 'a *)
Line 915: Line 915:


inc None;;
inc None;;
(* Exception: Failure "Undefined argument". *)</lang>
(* Exception: Failure "Undefined argument". *)</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
Line 927: Line 927:
However, variables can be "unbound" or "free". If a program tries to read such a variable, the current thread will be suspended until the variable's value becomes determined.
However, variables can be "unbound" or "free". If a program tries to read such a variable, the current thread will be suspended until the variable's value becomes determined.


<lang oz>declare X in
<syntaxhighlight lang="oz">declare X in


thread
thread
Line 938: Line 938:
{Delay 1000}
{Delay 1000}
{System.showInfo "Setting X."}
{System.showInfo "Setting X."}
X = 42</lang>
X = 42</syntaxhighlight>


Explicitly checking the status of a variable with <code>IsFree</code> is discouraged because it can introduce race conditions.
Explicitly checking the status of a variable with <code>IsFree</code> is discouraged because it can introduce race conditions.
Line 944: Line 944:
=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
In GP, undefined variables test equal to the monomial in the variable with the name of that variable. So to test if <var>v</var> is undefined, do
In GP, undefined variables test equal to the monomial in the variable with the name of that variable. So to test if <var>v</var> is undefined, do
<lang parigp>v == 'v</lang>
<syntaxhighlight lang="parigp">v == 'v</syntaxhighlight>


In PARI, you can do the same but the function <code>is_entry()</code> is more appropriate:
In PARI, you can do the same but the function <code>is_entry()</code> is more appropriate:
<lang C>is_entry("v") == NULL;</lang>
<syntaxhighlight lang="c">is_entry("v") == NULL;</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 953: Line 953:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>#!/usr/bin/perl -w
<syntaxhighlight lang="perl">#!/usr/bin/perl -w
use strict;
use strict;


Line 987: Line 987:
# Because most of the output is conditional, this serves as
# Because most of the output is conditional, this serves as
# a clear indicator that the program has run to completion.
# a clear indicator that the program has run to completion.
print "Done\n";</lang>
print "Done\n";</syntaxhighlight>


Results in:
Results in:
Line 999: Line 999:
{{libheader|Phix/basics}}
{{libheader|Phix/basics}}
Phix has a special unassigned value, that can be tested for using object(). (There is no offical way to "un-assign" a variable, though you could fairly easily do so with a bit of inline assembly.)
Phix has a special unassigned value, that can be tested for using object(). (There is no offical way to "un-assign" a variable, though you could fairly easily do so with a bit of inline assembly.)
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #004080;">object</span> <span style="color: #000000;">x</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">x</span>
Line 1,013: Line 1,013:
<span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">()</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,021: Line 1,021:


=={{header|PHP}}==
=={{header|PHP}}==
<lang php><?php
<syntaxhighlight lang="php"><?php
// Check to see whether it is defined
// Check to see whether it is defined
if (!isset($var))
if (!isset($var))
Line 1,053: Line 1,053:
// a clear indicator that the program has run to completion.
// a clear indicator that the program has run to completion.
echo "Done\n";
echo "Done\n";
?></lang>
?></syntaxhighlight>


Results in:
Results in:
Line 1,065: Line 1,065:
An internal symbol is initialized to NIL. Depending on the context, this is
An internal symbol is initialized to NIL. Depending on the context, this is
interpreted as "undefined". When called as a function, an error is issued:
interpreted as "undefined". When called as a function, an error is issued:
<lang PicoLisp>: (myfoo 3 4)
<syntaxhighlight lang="picolisp">: (myfoo 3 4)
!? (myfoo 3 4)
!? (myfoo 3 4)
myfoo -- Undefined
myfoo -- Undefined
?</lang>
?</syntaxhighlight>
The function 'default' can be used to initialize a variable if and only
The function 'default' can be used to initialize a variable if and only
if its current value is NIL:
if its current value is NIL:
<lang PicoLisp>: MyVar
<syntaxhighlight lang="picolisp">: MyVar
-> NIL
-> NIL


Line 1,084: Line 1,084:


: MyVar
: MyVar
-> 7</lang>
-> 7</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
In Pike variables are always defined. <code>UNDEFINED</code> is only used to indicate the nonexistence of a key or object member. <code>UNDEFINED</code> is not a value and can not be assigned. in such cases it is converted to <math>0</math>. <code>zero_type()</code> is used to test if a key exists or not:
In Pike variables are always defined. <code>UNDEFINED</code> is only used to indicate the nonexistence of a key or object member. <code>UNDEFINED</code> is not a value and can not be assigned. in such cases it is converted to <math>0</math>. <code>zero_type()</code> is used to test if a key exists or not:
<syntaxhighlight lang="pike">
<lang Pike>
> zero_type(UNDEFINED);
> zero_type(UNDEFINED);
Result: 1
Result: 1
Line 1,100: Line 1,100:
> zero_type(bar->baz);
> zero_type(bar->baz);
Result: 0
Result: 0
</syntaxhighlight>
</lang>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
The <code>Get-Variable</code> cmdlet gets the Windows PowerShell variables in the current console. Variables can be filtered by using the <code>-Name</code> parameter.
The <code>Get-Variable</code> cmdlet gets the Windows PowerShell variables in the current console. Variables can be filtered by using the <code>-Name</code> parameter.
If a variable doesn't exist an error is returned. Using the <code>-ErrorAction SilentlyContinue</code> parameter suppresses the error message and returns <code>$false</code>.
If a variable doesn't exist an error is returned. Using the <code>-ErrorAction SilentlyContinue</code> parameter suppresses the error message and returns <code>$false</code>.
<syntaxhighlight lang="powershell">
<lang PowerShell>
if (Get-Variable -Name noSuchVariable -ErrorAction SilentlyContinue)
if (Get-Variable -Name noSuchVariable -ErrorAction SilentlyContinue)
{
{
Line 1,114: Line 1,114:
$false
$false
}
}
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,121: Line 1,121:
PowerShell represents things like the file system, registry, functions, variables, etc. with '''providers''' known as PS drives.
PowerShell represents things like the file system, registry, functions, variables, etc. with '''providers''' known as PS drives.
One of those PS drives is Variable. <code>Variable:</code> contains all of the variables that are currently stored in memory.
One of those PS drives is Variable. <code>Variable:</code> contains all of the variables that are currently stored in memory.
<syntaxhighlight lang="powershell">
<lang PowerShell>
Get-PSProvider
Get-PSProvider
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,138: Line 1,138:
</pre>
</pre>
To access the Variable PS drive you'd use the same syntax as you would with the file system by specifying <code>Variable:\</code>.
To access the Variable PS drive you'd use the same syntax as you would with the file system by specifying <code>Variable:\</code>.
<syntaxhighlight lang="powershell">
<lang PowerShell>
Test-Path Variable:\noSuchVariable
Test-Path Variable:\noSuchVariable
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,146: Line 1,146:
</pre>
</pre>
If a variable doesn't exist, it technically has a value of <code>$null</code>. <code>$null</code> is an automatic variable that represents "does not exist."
If a variable doesn't exist, it technically has a value of <code>$null</code>. <code>$null</code> is an automatic variable that represents "does not exist."
<syntaxhighlight lang="powershell">
<lang PowerShell>
$noSuchVariable -eq $null
$noSuchVariable -eq $null
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,171: Line 1,171:
=={{header|PureBasic}}==
=={{header|PureBasic}}==
Variables are defined through a formal declaration or simply upon first use. Each variable is initialized to a value. PureBasic does not allow changing of a variable's status at runtime. It can be tested at compile-time and acted upon, however, it cannot be undefined once it is defined.
Variables are defined through a formal declaration or simply upon first use. Each variable is initialized to a value. PureBasic does not allow changing of a variable's status at runtime. It can be tested at compile-time and acted upon, however, it cannot be undefined once it is defined.
<lang PureBasic>If OpenConsole()
<syntaxhighlight lang="purebasic">If OpenConsole()


CompilerIf Defined(var, #PB_Variable)
CompilerIf Defined(var, #PB_Variable)
Line 1,191: Line 1,191:
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>
Sample output:
Sample output:
<pre>var is undefined at first check
<pre>var is undefined at first check
Line 1,199: Line 1,199:
In Python names, (variables), can be dynamically created and deleted at run time.
In Python names, (variables), can be dynamically created and deleted at run time.


<lang python># Check to see whether a name is defined
<syntaxhighlight lang="python"># Check to see whether a name is defined
try: name
try: name
except NameError: print "name is undefined at first check"
except NameError: print "name is undefined at first check"
Line 1,226: Line 1,226:
# Because most of the output is conditional, this serves as
# Because most of the output is conditional, this serves as
# a clear indicator that the program has run to completion.
# a clear indicator that the program has run to completion.
print "Done"</lang>
print "Done"</syntaxhighlight>


Results in:
Results in:
Line 1,237: Line 1,237:
=={{header|R}}==
=={{header|R}}==
There are four cases to consider. To test whether a varaible has previously been defined, use <code>exists</code>.
There are four cases to consider. To test whether a varaible has previously been defined, use <code>exists</code>.
<syntaxhighlight lang="r">
<lang r>
exists("x")
exists("x")
</syntaxhighlight>
</lang>


If you want to declare a variable with undefined contents, use <code>NULL</code>.
If you want to declare a variable with undefined contents, use <code>NULL</code>.
<syntaxhighlight lang="r">
<lang r>
x <- NULL
x <- NULL
</syntaxhighlight>
</lang>


If you want to declare a variable with missing values, use <code>NA</code>.
If you want to declare a variable with missing values, use <code>NA</code>.
<syntaxhighlight lang="r">
<lang r>
y <- c(1, 4, 9, NA, 25)
y <- c(1, 4, 9, NA, 25)
z <- c("foo", NA, "baz")
z <- c("foo", NA, "baz")
</syntaxhighlight>
</lang>
(Note that there are different types of <code>NA</code>, namely <code>NA_integer_</code>, <code>NA_real_</code>, <code>NA_character_</code>, <code>NA_complex_</code> and plain (logical) <code>NA</code>. In practice, you should hardly ever need to explicitly set which type of NA you are using, as it will be done automatically.)
(Note that there are different types of <code>NA</code>, namely <code>NA_integer_</code>, <code>NA_real_</code>, <code>NA_character_</code>, <code>NA_complex_</code> and plain (logical) <code>NA</code>. In practice, you should hardly ever need to explicitly set which type of NA you are using, as it will be done automatically.)


Finally, you test for arguments that haven't been passed into a function with <code>missing</code>.
Finally, you test for arguments that haven't been passed into a function with <code>missing</code>.
<syntaxhighlight lang="r">
<lang r>
print_is_missing <- function(x)
print_is_missing <- function(x)
{
{
Line 1,262: Line 1,262:
print_is_missing() # TRUE
print_is_missing() # TRUE
print_is_missing(123) # FALSE
print_is_missing(123) # FALSE
</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==
Line 1,269: Line 1,269:
recursive definitions. It can be grabbed explicitly with:
recursive definitions. It can be grabbed explicitly with:


<syntaxhighlight lang="racket">
<lang Racket>
-> (letrec ([x x]) x)
-> (letrec ([x x]) x)
#<undefined>
#<undefined>
</syntaxhighlight>
</lang>


However, it is not used as an implicit value for all (non-existent)
However, it is not used as an implicit value for all (non-existent)
Line 1,281: Line 1,281:
Raku has "interesting" values of undef, but unlike Perl 5, doesn't actually have a value named <tt>undef</tt>. Instead, several very different meanings of undefinedness are distinguished. First, <tt>Nil</tt> represents the absence of a value. The absence of a value cannot be stored. Instead, an attempt to assign <tt>Nil</tt> to a storage location causes that location to revert to its uninitialized state, however that is defined.
Raku has "interesting" values of undef, but unlike Perl 5, doesn't actually have a value named <tt>undef</tt>. Instead, several very different meanings of undefinedness are distinguished. First, <tt>Nil</tt> represents the absence of a value. The absence of a value cannot be stored. Instead, an attempt to assign <tt>Nil</tt> to a storage location causes that location to revert to its uninitialized state, however that is defined.


<lang perl6>my $x; $x = 42; $x = Nil; say $x.WHAT; # prints Any()</lang>
<syntaxhighlight lang="raku" line>my $x; $x = 42; $x = Nil; say $x.WHAT; # prints Any()</syntaxhighlight>


This <tt>Any</tt> is an example of another kind of undefined type, which is a typed undef. All reference types have an undefined value representing the type. You can think of it as a sort of "type gluon" that carries a type charge without being a "real" particle. Hence there are undefined values whose names represent types, such as <tt>Int</tt>, <tt>Num</tt>, <tt>Str</tt>, and all the other object types in Raku. As generic objects, such undefined values carry the same metaobject pointer that a real object of the type would have, without being instantiated as a real object. As such, these types are in the type hierarchy. For example, <tt>Int</tt> derives from <tt>Cool</tt>, <tt>Cool</tt> derives from <tt>Any</tt>, and <tt>Any</tt> derives from <tt>Mu</tt>, the most general undefined object (akin to Object in other languages). Since they are real objects of the type, even if undefined, they can be used in reasoning about the type. You don't have to instantiate a <tt>Method</tt> object in order to ask if <tt>Method</tt> is derived from <tt>Routine</tt>, for instance.
This <tt>Any</tt> is an example of another kind of undefined type, which is a typed undef. All reference types have an undefined value representing the type. You can think of it as a sort of "type gluon" that carries a type charge without being a "real" particle. Hence there are undefined values whose names represent types, such as <tt>Int</tt>, <tt>Num</tt>, <tt>Str</tt>, and all the other object types in Raku. As generic objects, such undefined values carry the same metaobject pointer that a real object of the type would have, without being instantiated as a real object. As such, these types are in the type hierarchy. For example, <tt>Int</tt> derives from <tt>Cool</tt>, <tt>Cool</tt> derives from <tt>Any</tt>, and <tt>Any</tt> derives from <tt>Mu</tt>, the most general undefined object (akin to Object in other languages). Since they are real objects of the type, even if undefined, they can be used in reasoning about the type. You don't have to instantiate a <tt>Method</tt> object in order to ask if <tt>Method</tt> is derived from <tt>Routine</tt>, for instance.


<lang perl6>say Method ~~ Routine; # Bool::True</lang>
<syntaxhighlight lang="raku" line>say Method ~~ Routine; # Bool::True</syntaxhighlight>


Variables default to <tt>Any</tt>, unless declared to be of another type:
Variables default to <tt>Any</tt>, unless declared to be of another type:
<lang perl6>my $x; say $x.WHAT; # Any()
<syntaxhighlight lang="raku" line>my $x; say $x.WHAT; # Any()
my Int $y; say $y.WHAT; # Int()
my Int $y; say $y.WHAT; # Int()
my Str $z; say $z.WHAT; # Str()</lang>
my Str $z; say $z.WHAT; # Str()</syntaxhighlight>


The user-interface for definedness are [http://design.raku.org/S12.html#Abstract_vs_Concrete_types type smilies] and the <tt>with</tt>-statement.
The user-interface for definedness are [http://design.raku.org/S12.html#Abstract_vs_Concrete_types type smilies] and the <tt>with</tt>-statement.


<lang perl6>my Int:D $i = 1; # if $i has to be defined you must provide a default value
<syntaxhighlight lang="raku" line>my Int:D $i = 1; # if $i has to be defined you must provide a default value
multi sub foo(Int:D $i where * != 0){ (0..100).roll / $i } # we will never divide by 0
multi sub foo(Int:D $i where * != 0){ (0..100).roll / $i } # we will never divide by 0
multi sub foo(Int:U $i){ die 'WELP! $i is undefined' } # because undefinedness is deadly
multi sub foo(Int:U $i){ die 'WELP! $i is undefined' } # because undefinedness is deadly
Line 1,300: Line 1,300:
with $i { say 'defined' } # as "if" is looking for Bool::True, "with" is looking for *.defined
with $i { say 'defined' } # as "if" is looking for Bool::True, "with" is looking for *.defined
with 0 { say '0 may not divide but it is defined' }
with 0 { say '0 may not divide but it is defined' }
</syntaxhighlight>
</lang>


There are further some [http://design.raku.org/S03.html operators] for your convenience.
There are further some [http://design.raku.org/S03.html operators] for your convenience.


<lang perl6>my $is-defined = 1;
<syntaxhighlight lang="raku" line>my $is-defined = 1;
my $ain't-defined = Any;
my $ain't-defined = Any;
my $doesn't-matter;
my $doesn't-matter;
Line 1,320: Line 1,320:
my $s = (f1() orelse f2()); # Please note the parentheses, which are needed because orelse is
my $s = (f1() orelse f2()); # Please note the parentheses, which are needed because orelse is
# much looser then infix:<=> .
# much looser then infix:<=> .
dd $s; # this be Bool::False</lang>
dd $s; # this be Bool::False</syntaxhighlight>


Finally, another major group of undefined values represents failures. Raku is designed with the notion that throwing exceptions is bad for parallel processing, so exceptions are thrown lazily; that is, they tend to be returned in-band instead as data, and are only thrown for real if not properly handled as exception data. (In which case, the exception is required to report the original difficulty accurately.) In order not to disrupt control flow and the synchronicity of event ordering, such failures are returned in-band as a normal values. And in order not to subvert the type system when it comes to return types, failure may be mixed into any reference type which produces an undefined, typed value which is also indicates the nature of the failure.
Finally, another major group of undefined values represents failures. Raku is designed with the notion that throwing exceptions is bad for parallel processing, so exceptions are thrown lazily; that is, they tend to be returned in-band instead as data, and are only thrown for real if not properly handled as exception data. (In which case, the exception is required to report the original difficulty accurately.) In order not to disrupt control flow and the synchronicity of event ordering, such failures are returned in-band as a normal values. And in order not to subvert the type system when it comes to return types, failure may be mixed into any reference type which produces an undefined, typed value which is also indicates the nature of the failure.
Line 1,327: Line 1,327:


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX program test if a (REXX) variable is defined or not defined. */
<syntaxhighlight lang="rexx">/*REXX program test if a (REXX) variable is defined or not defined. */
tlaloc = "rain god of the Aztecs." /*assign a value to the Aztec rain god.*/
tlaloc = "rain god of the Aztecs." /*assign a value to the Aztec rain god.*/
/*check if the rain god is defined. */
/*check if the rain god is defined. */
Line 1,346: Line 1,346:
if symbol(y)=="VAR" then say y ' is defined.'
if symbol(y)=="VAR" then say y ' is defined.'
else say y "isn't defined."
else say y "isn't defined."
/*stick a fork in it, we're all done. */</lang>
/*stick a fork in it, we're all done. */</syntaxhighlight>
'''output'''
'''output'''
<pre>
<pre>
Line 1,355: Line 1,355:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Undefined values
# Project : Undefined values


Line 1,364: Line 1,364:
islocal("y") + nl +
islocal("y") + nl +
islocal("z") + nl
islocal("z") + nl
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,373: Line 1,373:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby># Check to see whether it is defined
<syntaxhighlight lang="ruby"># Check to see whether it is defined
puts "var is undefined at first check" unless defined? var
puts "var is undefined at first check" unless defined? var


Line 1,387: Line 1,387:
# Because most of the output is conditional, this serves as
# Because most of the output is conditional, this serves as
# a clear indicator that the program has run to completion.
# a clear indicator that the program has run to completion.
puts "Done"</lang>
puts "Done"</syntaxhighlight>


Results in:
Results in:
Line 1,407: Line 1,407:
A pointer may have a ''null'' value:
A pointer may have a ''null'' value:


<lang Rust>use std::ptr;
<syntaxhighlight lang="rust">use std::ptr;


let p: *const i32 = ptr::null();
let p: *const i32 = ptr::null();
assert!(p.is_null());</lang>
assert!(p.is_null());</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
Line 1,424: Line 1,424:
=={{header|Sidef}}==
=={{header|Sidef}}==
Sidef variables are initialized with a default ''nil'' value, representing the absence of a value.
Sidef variables are initialized with a default ''nil'' value, representing the absence of a value.
<lang ruby>var x; # declared, but not defined
<syntaxhighlight lang="ruby">var x; # declared, but not defined
x == nil && say "nil value";
x == nil && say "nil value";
defined(x) || say "undefined";
defined(x) || say "undefined";
Line 1,436: Line 1,436:
x = nil;
x = nil;


defined(x) || say "undefined";</lang>
defined(x) || say "undefined";</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,452: Line 1,452:


However, we can check for the existence of a global binding with:
However, we can check for the existence of a global binding with:
<lang smalltalk>Smalltalk includesKey: #FooBar
<syntaxhighlight lang="smalltalk">Smalltalk includesKey: #FooBar
myNamespace includesKey: #Baz</lang>
myNamespace includesKey: #Baz</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
Tcl does not have undefined ''values'', but ''variables'' may be undefined by being not set.
Tcl does not have undefined ''values'', but ''variables'' may be undefined by being not set.
<lang tcl># Variables are undefined by default and do not need explicit declaration
<syntaxhighlight lang="tcl"># Variables are undefined by default and do not need explicit declaration


# Check to see whether it is defined
# Check to see whether it is defined
Line 1,480: Line 1,480:
if {![info exists var]} {puts "var is undefind at fourth check"}
if {![info exists var]} {puts "var is undefind at fourth check"}


puts "Done"</lang>
puts "Done"</syntaxhighlight>
Yields this output:
Yields this output:
<pre>
<pre>
Line 1,489: Line 1,489:


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
<lang bash>VAR1="VAR1"
<syntaxhighlight lang="bash">VAR1="VAR1"
echo ${VAR1:-"Not set."}
echo ${VAR1:-"Not set."}
echo ${VAR2:-"Not set."}</lang>
echo ${VAR2:-"Not set."}</syntaxhighlight>
<pre>VAR1
<pre>VAR1
Not set.</pre>
Not set.</pre>
Line 1,505: Line 1,505:


In conditional expressions, ''null'' as well as the Boolean value ''false'' are considered to be 'false'. All other values (including zero) are considered to be 'true'.
In conditional expressions, ''null'' as well as the Boolean value ''false'' are considered to be 'false'. All other values (including zero) are considered to be 'true'.
<lang ecmascript>var f = Fn.new {
<syntaxhighlight lang="ecmascript">var f = Fn.new {
System.print("'f' called.") // note no return value
System.print("'f' called.") // note no return value
}
}
Line 1,519: Line 1,519:


var v = null // explicitly assigned null
var v = null // explicitly assigned null
if (!v) System.print("v is %(v).")</lang>
if (!v) System.print("v is %(v).")</syntaxhighlight>


{{out}}
{{out}}
Line 1,532: Line 1,532:
=={{header|zkl}}==
=={{header|zkl}}==
Nothing is undefined in zkl (in theory). Numeric values like inf and NaN are "discouraged". "Void" is an object that is used as a "sentinel" for "I have no idea what the proper value should be" but it is just object that can be used like any other object.
Nothing is undefined in zkl (in theory). Numeric values like inf and NaN are "discouraged". "Void" is an object that is used as a "sentinel" for "I have no idea what the proper value should be" but it is just object that can be used like any other object.
<lang zkl>println(Void);
<syntaxhighlight lang="zkl">println(Void);
1+Void
1+Void
if(Void){} else { 23 }</lang>
if(Void){} else { 23 }</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>