Undefined values: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(Rename Perl 6 -> Raku, alphabetize, minor clean-up)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(18 intermediate revisions by 14 users not shown)
Line 1:
{{task|Programming language concepts}}For languages which have an explicit notion of an undefined value, identify and exercise those language's mechanisms for identifying and manipulating a variable's value's status as being undefined.
<br/><br/>
=={{header|6502 Assembly}}==
Every operation will return some 8-bit value, so there is no <code>null</code> in 6502 or anything like that. However, it is possible for certain actions to have '''undefined behavior''', for example, attempting to read from a write-only memory-mapped port might return any value from 0-255, depending on what was last on the data bus.
 
=={{header|68000 Assembly}}==
There is no "undefined" value as every instruction that is capable of altering the contents of a register will set the value of that register equal to some number between <tt>0</tt> and <tt>0xFFFFFFFF</tt>. Whether or not that value has any actual meaning, however, depends entirely on what action was taken. It is possible for certain actions to have '''undefined behavior''' such as:
* Reading from uninitialized memory (can return some garbage data that means nothing)
* Reading from a write-only hardware port
* Indexing an array out of bounds
 
In cases like these, what you get is dependent on what is stored at the memory read, or some other hardware-based factors out of the programmer's control. This is as close to an undefined value as you can really get.
 
=={{header|ActionScript}}==
ActionScript has a special '''undefined''' value which applies to untyped variables and properties of dynamic classes which have not been initialized.
<langsyntaxhighlight lang="actionscript">var foo; // untyped
var bar:*; // explicitly untyped
 
Line 10 ⟶ 20:
 
if (foo == undefined)
trace("foo is undefined"); // outputs "foo is undefined"</langsyntaxhighlight>
 
ActionScript also has a '''null''' value: see [[Null object#ActionScript]].
Line 21 ⟶ 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 one has the effect similar to Normalize_Scalars, but is [[GNAT]]-specific:
<syntaxhighlight lang="ada">
<lang Ada>
pragma Initialize_Scalars;
with Ada.Text_IO; use Ada.Text_IO;
Line 45 ⟶ 55:
end if;
end Invalid_Value;
</syntaxhighlight>
</lang>
Sample output:
<pre>
Line 63 ⟶ 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.
<langsyntaxhighlight lang="algol68">MODE R = REF BOOL;
R r := NIL;
 
Line 78 ⟶ 88:
(VOID):print(("u is EMPTY", new line))
OUT print(("u isnt EMPTY", new line))
ESAC</langsyntaxhighlight>
Output:
<pre>
Line 86 ⟶ 96:
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">undef: null
 
print undef</syntaxhighlight>
<lang arturo>undef: null
 
print undef</lang>
 
{{out}}
Line 100 ⟶ 109:
=={{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:
<langsyntaxhighlight lang="bbcbasic"> ok% = TRUE
ON ERROR LOCAL IF ERR<>26 REPORT : END ELSE ok% = FALSE
IF ok% THEN
Line 107 ⟶ 116:
PRINT "Not defined"
ENDIF
RESTORE ERROR</langsyntaxhighlight>
 
{{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:
<langsyntaxhighlight lang="bbcbasic"> PROCtest
END
Line 121 ⟶ 130:
!^array() = 0 : REM Set array to undefined state
ENDPROC</langsyntaxhighlight>
 
=={{header|C}}==
Line 130 ⟶ 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.
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
int main()
{
int junk, *junkp;
 
/* Print an unitialized variable! */
printf("junk: %d\n", junk);
 
/* Follow a pointer to unitialized memory! */
junkp = malloc(sizeof *junkp);
if (junkp)
printf("*junkp: %d\n", *junkp);
return 0;
}</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="csharp">string foo = null;</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="csharp">int i = null;</langsyntaxhighlight>
With .NET 2.0 there is an additional <code>Nullable<T></code> structure which enables those semantics for value types as well:
<langsyntaxhighlight lang="csharp">int? answer = null;
if (answer == null) {
answer = 42;
}</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="csharp">Nullable<int> answer = new Nullable<int>();
if (!answer.HasValue) {
answer = new Nullable<int>(42);
}</langsyntaxhighlight>
So it's a little compiler magic but in the end works just as one would expect.
 
=={{header|C++}}==
 
In C++, a variable that has not been initialized has an undefined value which cannot be tested or used in any
way. Attempting to use an undefined value results in undefined behavior. In the code below, anything could
happen. It may print '42', 'not 42', both, or nothing at all. The unexpected behavior happens because since
the behavior is undefined, the compiler can do whatever it wants. Most compilers will give a warning.
 
<syntaxhighlight lang="cpp">#include <iostream>
 
int main()
{
int undefined;
if (undefined == 42)
{
std::cout << "42";
}
if (undefined != 42)
{
std::cout << "not 42";
}
}</syntaxhighlight>
{{out}}
<pre>
? ? ?
</pre>
 
=={{header|Common Lisp}}==
Line 174 ⟶ 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:
 
<langsyntaxhighlight lang="lisp">
;; assumption: none of these variables initially exist
 
Line 184 ⟶ 220:
(boundp '*y*) -> T
 
(special-variable-p '*z*) -> NIL ;; *z* does not name a special variable</langsyntaxhighlight>
 
Furthermore, a variable which is bound can be made unbound:
 
<langsyntaxhighlight lang="lisp">
(makunbound '*y*) ;; *y* no longer has a value; it is erroneous to evaluate *y*
 
(setf *y* 43) ;; *y* is bound again.</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="lisp">
(defvar *dyn*) ;; special, no binding
 
Line 203 ⟶ 239:
(list (boundp '*dyn*) *dyn* (boundp 'lex) lex)) -> (T NIL NIL NIL)
 
(boundp '*global*) -> NIL</langsyntaxhighlight>
 
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 209 ⟶ 245:
=={{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.
<langsyntaxhighlight lang="d">void main() {
// Initialized:
int a = 5;
Line 227 ⟶ 263:
double[] bbb = void;
int[3] eee = void;
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
Line 233 ⟶ 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.
<langsyntaxhighlight lang="delphi">var
P: PInteger;
begin
Line 245 ⟶ 281:
Dispose(P); //Release memory allocated by New
end;
end;</langsyntaxhighlight>
 
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 251 ⟶ 287:
=={{header|Déjà Vu}}==
There is no undefined value in Déjà Vu. Instead, trying to access an undefined variable raises an exception.
<langsyntaxhighlight lang="dejavu">try:
bogus
catch name-error:
!print "There is *no* :bogus in the current context"
return
!print "You won't see this."</langsyntaxhighlight>
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 269 ⟶ 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:
 
<langsyntaxhighlight lang="e">if (foo == bar || (def baz := lookup(foo)) != null) {
...
}</langsyntaxhighlight>
 
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 279 ⟶ 315:
=={{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.
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( undefined_values ).
 
Line 290 ⟶ 326:
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] ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 301 ⟶ 337:
 
ERRE hasn't the concept of un-initialised or undefined variable: every scalar variable is allocated at runtime with value zero if numeric or value "" if string. Array type variables must be declared but follow the same initialisation rules of scalars.
 
=={{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:
<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:
<syntaxhighlight lang="factor">TUPLE: foo bar ;
foo new bar>> . ! f
 
TUPLE: my-tuple { n integer } ;
my-tuple new n>> . ! 0</syntaxhighlight>
 
Dynamic variables (and indeed all words) are initialized to <code>f</code>:
<syntaxhighlight lang="factor">SYMBOL: n
n get . ! f
 
\ + get . ! f</syntaxhighlight>
 
Finally, Factor does not allow lexical variables to be declared without initialization:
 
<syntaxhighlight lang="factor">[let
2 :> n ! There is no other way!
0 1 :> ( a b )
]</syntaxhighlight>
 
=={{header|Forth}}==
Forth does not have undefined values, but defined and undefined variables can be checked.
<syntaxhighlight lang="forth">
[undefined] var [if] .( var is undefined at first check) cr [then]
 
marker forget-var
 
variable var
 
[defined] var [if] .( var is defined at second check) cr [then]
 
forget-var
 
[undefined] var [if] .( var is undefined at third check) cr [then]
</syntaxhighlight>
{{out}}
<pre>
var is undefined at first check
var is defined at second check
var is undefined at third check
</pre>
 
=={{header|Fortran}}==
Line 308 ⟶ 390:
 
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
<syntaxhighlight lang Fortran="fortran">IsNaN(x)</langsyntaxhighlight>
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}}==
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:
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim i As Integer '' initialized to 0 by default
Line 320 ⟶ 402:
 
Print i, j, k
Sleep</langsyntaxhighlight>
 
{{out}}
Line 329 ⟶ 411:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">IsBound(a);
# true
 
Line 335 ⟶ 417:
 
IsBound(a);
# false</langsyntaxhighlight>
 
=={{header|Go}}==
Line 345 ⟶ 427:
# Successful (non panicking) use of initialized objects.
# One more quirky little feature involving a type switch on a nil interface.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 441 ⟶ 523:
close(c)
fmt.Println("channel closed")
}</langsyntaxhighlight>
Output:
<pre>
Line 466 ⟶ 548:
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,
 
<langsyntaxhighlight lang="haskell">main = print $ "Incoming error--" ++ undefined
-- When run in GHC:
-- "Incoming error--*** Exception: Prelude.undefined</langsyntaxhighlight>
 
This isn't quite as dangerous as it sounds because of Haskell's laziness. For example, this program:
 
<langsyntaxhighlight lang="haskell">main = print $ length [undefined, undefined, 1 `div` 0]</langsyntaxhighlight>
 
prints <code>3</code>, since <code>length</code> doesn't need to evaluate any of the elements of its input.
Line 478 ⟶ 560:
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
 
<langsyntaxhighlight lang="haskell">resurrect 0 = error "I'm out of orange smoke!"</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="haskell">undefined :: a
undefined = error "Prelude.undefined"</langsyntaxhighlight>
 
Since <code>undefined</code> causes an exception, the usual exception handling mechanism can be used to catch it:
 
<langsyntaxhighlight lang="haskell">import Control.Exception (catch, evaluate, ErrorCall)
import System.IO.Unsafe (unsafePerformIO)
import Prelude hiding (catch)
Line 502 ⟶ 584:
main = do
print $ safeHead ([] :: String)
print $ safeHead ["str"]</langsyntaxhighlight>
 
== Icon and Unicon ==
Line 510 ⟶ 592:
 
==={{header|Unicon}}===
<langsyntaxhighlight Uniconlang="unicon">global G1
 
procedure main(arglist)
Line 524 ⟶ 606:
write((localnames|paramnames|staticnames|globalnames)(&current,0)) # ... visible in the current co-expression at this calling level (0)
return
end</langsyntaxhighlight>
 
The output looks like:
Line 543 ⟶ 625:
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
nc;:'foo bar'
0 _1</langsyntaxhighlight>
 
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 552 ⟶ 634:
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'
1 1
Line 559 ⟶ 641:
bar=:99
nc;:'foo bar'
_1 0</langsyntaxhighlight>
 
=={{header|Java}}==
Line 565 ⟶ 647:
 
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.
<langsyntaxhighlight lang="java">String string = null; // the variable string is undefined
System.out.println(string); //prints "null" to std out
System.out.println(string.length()); // dereferencing null throws java.lang.NullPointerException</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="java">int i = null; // compilation error: incompatible types, required: int, found: <nulltype>
if (i == null) { // compilation error: incomparable types: int and <nulltype>
i = 1;
}</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="java">Integer i = null; // variable i is undefined
if (i == null) {
i = 1;
}</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="javascript">var a;
 
typeof(a) === "undefined";
Line 594 ⟶ 676:
obj.c === 42;
delete obj.c;
typeof(obj.c) === "undefined";</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="javascript">var a;
a === void 0; // true
b === void 0; // throws a ReferenceError</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="jq">{}["key"] #=> null</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="jq">1/0 == null #=>false</langsyntaxhighlight>
 
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 612 ⟶ 694:
 
For example, suppose it is agreed that the "sum" of the elements of an empty array should be null. Then one can simply write:
<langsyntaxhighlight lang="jq">def sum: reduce .[] as $x (null; . + $x);</langsyntaxhighlight>
 
=={{header|Julia}}==
Line 625 ⟶ 707:
</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:
<langsyntaxhighlight lang="julia">
julia> arr = [1, 2, nothing, 3]
4-element Array{Union{Nothing, Int64},1}:
Line 654 ⟶ 736:
missing
8
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
Line 664 ⟶ 746:
 
Here are some simple examples illustrating these points:
<langsyntaxhighlight lang="scala">// version 1.1.2
 
class SomeClass
Line 701 ⟶ 783:
println(e)
}
}</langsyntaxhighlight>
 
{{out}}
Line 711 ⟶ 793:
=={{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():
<langsyntaxhighlight lang="lingo">put var
-- <Void>
put var=VOID
Line 719 ⟶ 801:
var = 23
put voidP(var)
-- 0</langsyntaxhighlight>
 
=={{header|Logo}}==
Line 726 ⟶ 808:
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.
 
<langsyntaxhighlight lang="logo">; procedures
to square :x
output :x * :x
Line 744 ⟶ 826:
ern "n
show name? "n ; false
show :n ; n has no value</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight LOLCODElang="lolcode">HAI 1.3
 
I HAS A foo BTW, INISHULIZD TO NOOB
Line 765 ⟶ 847:
OIC
 
KTHXBYE</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">print( a )
 
local b
Line 776 ⟶ 858:
b = 5
end
print( b )</langsyntaxhighlight>
Output:
<pre>nil
Line 782 ⟶ 864:
5</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Mathematica is a symbolic mathematical software. Variables without given values are treated as symbols.
<syntaxhighlight lang="mathematica">a
<lang Mathematica>a
-> a
 
a + a
-> 2 a
 
ValueQ[a]
-> False
 
a = 5
-> 5
 
ValueQ[a]
-> True</langsyntaxhighlight>
Mathematica also has a build-in symbol "Undefined", representing a quantity with no defined value.
<langsyntaxhighlight Mathematicalang="mathematica">ConditionalExpression[a, False]
->Undefined</langsyntaxhighlight>
Mathematical expressions containing Undefined evaluate to Undefined:
<langsyntaxhighlight Mathematicalang="mathematica">Sin[Undefined]
-> Undefined </langsyntaxhighlight>
Of course you can assign Undefined to be the value of a variable. Here "Undefined" is itself a value.
<langsyntaxhighlight Mathematicalang="mathematica">a = Undefined
-> Undefined
 
a
-> Undefined
 
ValueQ[a]
-> True</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
 
If a variable is generated without defing a value, e.g. with
<syntaxhighlight lang Matlab="matlab"> global var; </langsyntaxhighlight>
the variable is empty, and can be tested with
<syntaxhighlight lang Matlab="matlab"> isempty(var) </langsyntaxhighlight>
 
For numerical values (e.g. vectors or arrays) with a predefined size, often not-a-numbers (NaN's) user used to indicate missing values,
<langsyntaxhighlight Matlablang="matlab"> var = [1, 2, NaN, 0/0, inf-inf, 5] </langsyntaxhighlight>
These can be tested with:
<syntaxhighlight lang Matlab="matlab"> isnan(var) </langsyntaxhighlight>
 
<pre>
Line 834 ⟶ 910:
=={{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>
<langsyntaxhighlight MUMPSlang="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</langsyntaxhighlight>
 
=={{header|Nim}}==
In Nim, all variables are initialized to a default value which is a binary zero. If this value is incompatible with the variable type, a warning is emitted.
 
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:
<syntaxhighlight lang="nim">var a {.noInit.}: array[1_000_000, int]
 
# For a proc, {.noInit.} means that the result is not initialized.
proc p(): array[1000, int] {.noInit.} =
for i in 0..999: result[i] = i</syntaxhighlight>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">(* There is no undefined value in OCaml,
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 *)
Line 851 ⟶ 937:
 
inc None;;
(* Exception: Failure "Undefined argument". *)</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 863 ⟶ 949:
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.
 
<langsyntaxhighlight lang="oz">declare X in
 
thread
Line 874 ⟶ 960:
{Delay 1000}
{System.showInfo "Setting X."}
X = 42</langsyntaxhighlight>
 
Explicitly checking the status of a variable with <code>IsFree</code> is discouraged because it can introduce race conditions.
Line 880 ⟶ 966:
=={{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
<langsyntaxhighlight lang="parigp">v == 'v</langsyntaxhighlight>
 
In PARI, you can do the same but the function <code>is_entry()</code> is more appropriate:
<langsyntaxhighlight Clang="c">is_entry("v") == NULL;</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 889 ⟶ 975:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!/usr/bin/perl -w
use strict;
 
Line 923 ⟶ 1,009:
# Because most of the output is conditional, this serves as
# a clear indicator that the program has run to completion.
print "Done\n";</langsyntaxhighlight>
 
Results in:
Line 933 ⟶ 1,019:
 
=={{header|Phix}}==
{{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.)
<!--<syntaxhighlight lang="phix">-->
<lang Phix>object x
<span style="color: #004080;">object</span> <span style="color: #000000;">x</span>
 
procedure test()
<span style="color: #008080;">procedure</span> <span style="color: #000000;">test</span><span style="color: #0000FF;">()</span>
if object(x) then
<span style="color: #008080;">if</span> <span style="color: #004080;">object</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
puts(1,"x is an object\n")
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"x is an object\n"</span><span style="color: #0000FF;">)</span>
else
<span style="color: #008080;">else</span>
puts(1,"x is unassigned\n")
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"x is unassigned\n"</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
 
test()
<span style="color: #000000;">test</span><span style="color: #0000FF;">()</span>
x = 1
<span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
test()</lang>
<span style="color: #000000;">test</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 954 ⟶ 1,043:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
// Check to see whether it is defined
if (!isset($var))
Line 986 ⟶ 1,075:
// a clear indicator that the program has run to completion.
echo "Done\n";
?></langsyntaxhighlight>
 
Results in:
Line 998 ⟶ 1,087:
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:
<langsyntaxhighlight PicoLisplang="picolisp">: (myfoo 3 4)
!? (myfoo 3 4)
myfoo -- Undefined
?</langsyntaxhighlight>
The function 'default' can be used to initialize a variable if and only
if its current value is NIL:
<langsyntaxhighlight PicoLisplang="picolisp">: MyVar
-> NIL
 
Line 1,017 ⟶ 1,106:
 
: MyVar
-> 7</langsyntaxhighlight>
 
=={{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:
<syntaxhighlight lang="pike">
<lang Pike>
> zero_type(UNDEFINED);
Result: 1
Line 1,033 ⟶ 1,122:
> zero_type(bar->baz);
Result: 0
</syntaxhighlight>
</lang>
 
=={{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.
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)
{
Line 1,047 ⟶ 1,136:
$false
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,054 ⟶ 1,143:
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.
<syntaxhighlight lang="powershell">
<lang PowerShell>
Get-PSProvider
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,071 ⟶ 1,160:
</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>.
<syntaxhighlight lang="powershell">
<lang PowerShell>
Test-Path Variable:\noSuchVariable
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,079 ⟶ 1,168:
</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."
<syntaxhighlight lang="powershell">
<lang PowerShell>
$noSuchVariable -eq $null
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,088 ⟶ 1,177:
 
=={{header|Prolog}}==
Prolog has two predicates to know if a variable is instanciedinstantiated or not : '''var/1''' and '''nonvar/1''' <br>
<pre>?- var(Y).
true.
Line 1,104 ⟶ 1,193:
=={{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.
<langsyntaxhighlight PureBasiclang="purebasic">If OpenConsole()
 
CompilerIf Defined(var, #PB_Variable)
Line 1,124 ⟶ 1,213:
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>var is undefined at first check
Line 1,132 ⟶ 1,221:
In Python names, (variables), can be dynamically created and deleted at run time.
 
<langsyntaxhighlight lang="python"># Check to see whether a name is defined
try: name
except NameError: print "name is undefined at first check"
Line 1,159 ⟶ 1,248:
# Because most of the output is conditional, this serves as
# a clear indicator that the program has run to completion.
print "Done"</langsyntaxhighlight>
 
Results in:
Line 1,170 ⟶ 1,259:
=={{header|R}}==
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")
</syntaxhighlight>
</lang>
 
If you want to declare a variable with undefined contents, use <code>NULL</code>.
<syntaxhighlight lang="r">
<lang r>
x <- NULL
</syntaxhighlight>
</lang>
 
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)
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.)
 
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)
{
Line 1,195 ⟶ 1,284:
print_is_missing() # TRUE
print_is_missing(123) # FALSE
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
Line 1,202 ⟶ 1,291:
recursive definitions. It can be grabbed explicitly with:
 
<syntaxhighlight lang="racket">
<lang Racket>
-> (letrec ([x x]) x)
#<undefined>
</syntaxhighlight>
</lang>
 
However, it is not used as an implicit value for all (non-existent)
Line 1,212 ⟶ 1,301:
=={{header|Raku}}==
(formerly Perl 6)
Perl 6Raku 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.
 
<syntaxhighlight lang="raku" perl6line>my $x; $x = 42; $x = Nil; say $x.WHAT; # prints Any()</langsyntaxhighlight>
 
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 Perl 6Raku. 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.
 
<syntaxhighlight lang="raku" perl6line>say Method ~~ Routine; # Bool::True</langsyntaxhighlight>
 
Variables default to <tt>Any</tt>, unless declared to be of another type:
<syntaxhighlight lang="raku" perl6line>my $x; say $x.WHAT; # Any()
my Int $y; say $y.WHAT; # Int()
my Str $z; say $z.WHAT; # Str()</langsyntaxhighlight>
 
The user-interface for definedness are [http://design.perl6raku.org/S12.html#Abstract_vs_Concrete_types type smilies] and the <tt>with</tt>-statement.
 
<syntaxhighlight lang="raku" perl6line>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:U $i){ die 'WELP! $i is undefined' } # because undefinedness is deadly
Line 1,233 ⟶ 1,322:
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' }
</syntaxhighlight>
</lang>
 
There are further some [http://design.perl6raku.org/S03.html operators] for your convenience.
 
<syntaxhighlight lang="raku" perl6line>my $is-defined = 1;
my $ain't-defined = Any;
my $doesn't-matter;
Line 1,253 ⟶ 1,342:
my $s = (f1() orelse f2()); # Please note the parentheses, which are needed because orelse is
# much looser then infix:<=> .
dd $s; # this be Bool::False</langsyntaxhighlight>
 
Finally, another major group of undefined values represents failures. Perl 6Raku 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.
 
Native storage types work under different rules, since most native types cannot represent failure, or even undefinedness. Any attempt to assign a value to a storage location that cannot represent a failure will cause an exception to be thrown.
 
=={{header|REXX}}==
<langsyntaxhighlight 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.*/
/*check if the rain god is defined. */
Line 1,279 ⟶ 1,368:
if symbol(y)=="VAR" then say y ' is defined.'
else say y "isn't defined."
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''output'''
<pre>
Line 1,288 ⟶ 1,377:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Undefined values
 
Line 1,297 ⟶ 1,386:
islocal("y") + nl +
islocal("z") + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,306 ⟶ 1,395:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby"># Check to see whether it is defined
puts "var is undefined at first check" unless defined? var
 
Line 1,320 ⟶ 1,409:
# Because most of the output is conditional, this serves as
# a clear indicator that the program has run to completion.
puts "Done"</langsyntaxhighlight>
 
Results in:
Line 1,327 ⟶ 1,416:
Done
</pre>
 
=={{header|Rust}}==
All variables in Rust must have defined type and value.
 
For the representation of a value which might not be present, the standard library offers wrapper type <code>Option</code>.
<code>Option</code> has two variants: <code>Some</code> (holding a value) and <code>None</code> (indicating the absence of any value):
<code>Option</code> is a regular <code>enum</code> type and there is nothing special about it, except for its broad usage.
 
Rust supports raw pointers.
Pointers are used for interoperability with other languages and for low-level unsafe operations.
Safe Rust code can't use pointers as effective use of a pointer (dereferencing it) requires <code>unsafe</code> block.
A pointer may have a ''null'' value:
 
<syntaxhighlight lang="rust">use std::ptr;
 
let p: *const i32 = ptr::null();
assert!(p.is_null());</syntaxhighlight>
 
=={{header|Scala}}==
Line 1,340 ⟶ 1,446:
=={{header|Sidef}}==
Sidef variables are initialized with a default ''nil'' value, representing the absence of a value.
<langsyntaxhighlight lang="ruby">var x; # declared, but not defined
x == nil && say "nil value";
defined(x) || say "undefined";
Line 1,352 ⟶ 1,458:
x = nil;
 
defined(x) || say "undefined";</langsyntaxhighlight>
{{out}}
<pre>
Line 1,364 ⟶ 1,470:
In Smalltalk, all variables are automatically initialized to nil. This includes instance variables (an object's private slots), class variables and locals. Also global and namespace bindings can only be created by passing an existing value (typically also: nil) to the creation message (at:put:). This is part of the language's specification, not implementation specific. Thus a variable cannot ever be undefined.
 
Sending a message (aka performing a virtual function call) to the nil object results in an Exceptionexception, which can be caught if desired.
In other words, there is no segmentation violation or core dump, but well defined behavior in this situation. Notice that nil is also an instance of a class, UndefinedObject (actually its only singleton instance). And that UndefinedObject does implement a few messages (for example: isNil, notNil, printOn: etc.)
 
However, we can check for the existence of a global binding with:
<langsyntaxhighlight lang="smalltalk">Smalltalk includesKey: #FooBar
myNamespace includesKey: #Baz</langsyntaxhighlight>
 
=={{header|Tcl}}==
Tcl does not have undefined ''values'', but ''variables'' may be undefined by being not set.
<langsyntaxhighlight lang="tcl"># Variables are undefined by default and do not need explicit declaration
 
# Check to see whether it is defined
Line 1,396 ⟶ 1,502:
if {![info exists var]} {puts "var is undefind at fourth check"}
 
puts "Done"</langsyntaxhighlight>
Yields this output:
<pre>
Line 1,405 ⟶ 1,511:
 
=={{header|UNIX Shell}}==
<langsyntaxhighlight lang="bash">VAR1="VAR1"
echo ${VAR1:-"Not set."}
echo ${VAR2:-"Not set."}</langsyntaxhighlight>
<pre>VAR1
Not set.</pre>
 
=={{header|Wren}}==
The closest Wren has to an 'undefined' value is '''null''' though, technically, this is the only instance of the Null class.
 
Wren is dynamically typed and so ''null'' can be assigned to any variable.
 
In practice is it used to indicate the absence of a value. So, a function or method which doesn't otherwise return anything returns ''null'' and, if a map doesn't contain a key, an attempted look-up using that key returns ''null''.
 
If a variable is simply declared but not assigned a value, then its value is ''null''.
 
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'.
<syntaxhighlight lang="wren">var f = Fn.new {
System.print("'f' called.") // note no return value
}
 
var res = f.call()
System.print("The value returned by 'f' is %(res).")
 
var m = {} // empty map
System.print("m[1] is %(m[1]).")
 
var u // declared but not assigned a value
System.print("u is %(u).")
 
var v = null // explicitly assigned null
if (!v) System.print("v is %(v).")</syntaxhighlight>
 
{{out}}
<pre>
'f' called.
The value returned by 'f' is null.
m[1] is null.
u is null.
v is null.
</pre>
 
=={{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.
<langsyntaxhighlight lang="zkl">println(Void);
1+Void
if(Void){} else { 23 }</langsyntaxhighlight>
{{out}}
<pre>
Line 1,423 ⟶ 1,564:
</pre>
 
=={{header|Z80 Assembly}}==
Nothing is truly "undefined" since any operation will return some 8-bit or 16-bit number. It's more of a question of "does this value mean anything at all." There are actions that will result in "undefined" (read: inconsistent) behavior:
 
* Reading from the <code>R</code> register (returns some value that relates to dynamic memory refresh)
* Reading from uninitialized memory (returns whatever happens to be there)
* Using <code>IN</code> commands on a port that isn't connected to the CPU, or reading from a write-only port
 
{{omit from|6502 Assembly}}
{{omit from|68000 Assembly}}
{{omit from|8080 Assembly}}
{{omit from|8086 Assembly}}
{{omit from|ARM Assembly}}
{{omit from|MIPS Assembly}}
{{omit from|X86 Assembly}}
{{omit from|Z80 Assembly}}
{{omit from|GUISS}}
{{omit from|ACL2}}
9,476

edits