Special variables: Difference between revisions
Content deleted Content added
Forth |
PascalABC.NET |
||
(145 intermediate revisions by 64 users not shown) | |||
Line 1:
{{task|Basic language learning}}[[Category:Special variables]]
Special variables have a predefined meaning within a computer programming language.
;Task:
List the special variables used within the language.
<br><br>
=={{header|11l}}==
Refer to [https://11l-lang.org/doc/built-in-global-vars Built-in global variables] for the complete special variables (those variables are global).
=={{header|6502 Assembly}}==
The first 256 bytes of the CPU's address space are collectively known as "zero page RAM" and are common to all 6502 computers (except the custom 6502-based Hu6280 used in the PC Engine/TurboGrafx16.) This section of RAM is faster to load from, as the instructions that use it only take one byte to represent the memory address rather than two. On some implementations, certain zero-page RAM addresses are special, such as address $00 on Commodore 64 (which controls the memory management unit) and address $FF on Easy6502 (which contains the last keyboard input). In addition to loading faster, only the zero page can used indexed indirect addressing modes (the only exception being <code>JMP</code>, which CANNOT jump indirectly using zero page unless you pad it with a high byte of 00.)
The 16-bit 65816 and the Motorola 6809 (which are very similar to the 6502) call the zero page the "direct page" because it can be relocated on those systems. They have a dedicated register which tells the CPU where the direct page actually is. Like on the 6502, it's only 256 bytes in size. This allows the programmer to improve their program's performance by moving the direct page to wherever the majority of the loading will be taking place. Your code may cause problems if you load from the "wrong" direct page, however, so be careful!
=={{header|Ada}}==
Ada has no special variables in the standard namespace, nor are any such variables commonplace in packages, almost all are constants or private variables changed through functions.
The closest thing Ada has to special variables are attributes, which are of an object oriented nature dependant on their prefix. Examples:
* When X is of an array type, X'First denotes the first index of the array (Ada arrays are not limited to starting at 0 or 1).
* When X is of a scalar type, X'First denotes the lower bound of that type.
* X'Size gives the number of bits of memory type X is stored as, but can also be assigned to, to force the program to store the type in that number of bits. (Provided its more than the minimum)
* For example, a 2 bit record (structure) X might be stored as a byte by default as a speed optimization, but X'Size := 2; would force it to be stored as two bits.
There are far too many attributes to list here, but a standard informative list can be found in Annex K of the documentation if you have it installed.
Or Here: [http://www2.adacore.com/gap-static/GNAT_Book/html/aarm/AA-K.html Annex K - Language-Defined Attributes]
=={{header|ALGOL 68}}==
Line 6 ⟶ 31:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
<
FORMAT f = $g": ["g"]"l$;
Line 61 ⟶ 86:
END CO
));
SKIP</
Sample output:
<pre>
Line 94 ⟶ 119:
]
</pre>
===[[ALGOL 68G]]===
{{wont work with|ALGOL 68|Revision 1 - too many extensions to language used, but constants can be defined in a custom prelude.}}
Line 99 ⟶ 125:
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
[[ALGOL 68G]] provides some further constants to the scientifically motivated coder:
<
printf(($g": [", g, "] & [",g,"]"l$,
Line 213 ⟶ 239:
" joule", mksa joule, cgs joule,
" erg", mksa erg, cgs erg
))</
Output:
<pre>
Line 328 ⟶ 354:
erg: [+1.00000000000000e -7] & [+1.00000000000000e +0]
</pre>
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">% the Algol W standard environment includes the following standard variables: %
integer I_W % field width for integer output %
integer R_W % field width for real output %
integer R_D % number of decimal places for real output %
string(1) R_FORMAT % format for real output:
S - "scaled" normalised mantissa with exponent
A - "aligned" fixed point format
F - "free" either scaled or aligned as appropriate
for the value and field width
%
integer S_W % separator width - number of spaces following non-string output items %
integer MAXINTEGER % largest integer value %
real EPSILON % largest positive real number such that 1 + epsilon = 1 %
long real LONGEPSILON % largest positive long real number such that 1 + longepsilon = 1 %
long real MAXREAL % largest real number %
long real PI % approximation to pi %
% the following reference(EXCEPTION) variables control how errors are handled:
ENDFILE - end-of-file
OVFL - overflow
UNFL - underflow
DIVZERO - division by zero
INTOVFL - integer overflow
INTDIVZERO - integer division by zero or modulo 0
SQRTERR - invalid SQRT parameter
EXPERR - invalid EXP parameter
LNLOGERR - invalid LN or LOG parameter
SINCOSERR - invalid SIN or COS parameter
The EXCEPTION record is defined as follows:
record EXCEPTION( logical XCPNOTED - true if the exception has occurred
; integer XCPLIMIT - number of times the exception can occur
before the program terminates
, XCPACTION - if the program continues, controls how to
replace the erroneous value
; logical XCPMARK - true if an error message should be printed
even if the program continues
; string(64) XCPMSG - message to describe the exception
)
if the relevant EXCEPTION variable is null, the exception is ignored,
otherwise it is processed according to the settings of XCPLIMIT etc.
%</syntaxhighlight>
=={{header|Arturo}}==
There are no "special" variables in Arturo, as such. There are pre-defined, built-in functions & constants but every symbol can be re-defined at will, even during runtime.
=={{header|AutoHotkey}}==
Refer to [http://www.autohotkey.com/docs/Variables.htm#BuiltIn Built-in Variables] for the complete special variables (those variables are global, except noticed).
=={{header|AWK}}==
Line 350 ⟶ 430:
* RSTART - An informative variable that provides the start index of the currently matched substring
* SUBSEP - A control variable that specifies the subscript separator for multidimensional arrays
=={{header|Batch File}}==
By typing the <code>SET</code> command (without any parameters) in the command prompt, it will display the current environment variables and their current values.<br>
However, there are some special variables that are not listed in the variables displayed by the SET command because their values might change over time. These variables are as follows:<br>
<pre>%CD% - expands to the current directory string.
%DATE% - expands to current date using same format as DATE command.
%TIME% - expands to current time using same format as TIME command.
%RANDOM% - expands to a random decimal number between 0 and 32767.
%ERRORLEVEL% - expands to the current ERRORLEVEL value
%CMDEXTVERSION% - expands to the current Command Processor Extensions
version number.
%CMDCMDLINE% - expands to the original command line that invoked the
Command Processor.
%HIGHESTNUMANODENUMBER% - expands to the highest NUMA node number
on this machine.</pre>
(Source: by typing <code>SET/?</code> command in the command prompt)
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
The special (system) variables are as follows:
<pre>
@% The number output format control variable
@cmd$ The command line of a 'compiled' program
@dir$ The directory (folder) from which the program was loaded
@flags% An integer incorporating BBC BASIC's control flags
@hcsr% The handle of the mouse pointer (cursor)
@haccel% The handle of the keyboard accelerator, if used
@hevent% The handle of the event used to prevent blocking in serial I/O
@hfile%() An array of file handles indexed by channel number
@hmdi% The Multiple Document Interface window handle (if any)
@hwacc% The window handle to which keyboard accelerator commands should be sent
@hwnd% The 'window handle' for the main (output) window
@hwo% The handle of the WAVEOUTPUT device
@hpal% The handle for the colour palette
@ispal% A Boolean which is non-zero if the display is paletted
@lib$ The directory (folder) containing the library files
@lparam% The LPARAM value (for use with ON MOUSE, ON MOVE and ON SYS)
@memhdc% The 'device context' for the main (output) window
@midi% The MIDI device ID (non-zero if a MIDI file is playing)
@msg% The MSG value (for use with ON MOUSE, ON MOVE and ON SYS)
@ox% The horizontal offset (in pixels) between the output bitmap and the window contents
@oy% The vertical offset (in pixels) between the output bitmap and the window contents
@prthdc% The 'device context' for the current printer (if any)
@tmp$ The temporary directory (folder)
@usr$ The user's Documents directory (folder)
@vdu% A pointer to the text and graphics parameters
@vdu{} A structure containing the main text and graphics variables
@wparam% The WPARAM value (for use with ON MOUSE, ON MOVE and ON SYS)
</pre>
=={{header|bc}}==
There are three special variables:
* <code>scale</code>: determines how many digits after the decimal point a result of an expression will have (possible integer values from 0 to <code>BC_SCALE_MAX</code>, i.e. an implementation-specific maximum; initial value is 0)
* <code>ibase</code>: the input radix (possible integer values from 2 to 16; initial value is 10)
* <code>obase</code>: the output radix (possible integer values from 2 to <code>BC_BASE_MAX</code>; initial value is 10)
{{Works with|GNU bc}}
The GNU implementation adds another special variable, <code>last</code>, that contains the value of the last printed number.
=={{header|Bracmat}}==
Every function has a local variable <code>arg</code>. It is the function's actual argument. Pattern matching is used to dissect the argument, if needed. Functions in a pattern have an additional argument, <code>sjt</code>, which is bound to (part of) the subject of the pattern match operation. It is the part of the subject that the function, in the role of a pattern, attempts to match. These variables can be reassigned.
The names of the built-in functions <code>alc, arg, asc, chr, chu, clk, d2x, dbg, den, div, fil, flg, glf, fre, get, low, lst, mem, mod, new, pee, pok, put, ren, rev, rmv, sim, str, swi, sys, tbl, upp, utf, whl, x2d</code> can be used as variable names or names of user defined object member functions, but not as names of user defined functions. Conversely, the name <code>hash</code> can be used for user defined functions, but not for variables. Currentlty, <code>hash</code> is the only predefined object type.
If Bracmat starts in interactive mode, a few more variables are predefined: <code>!v</code> evaluates to a string telling which version of Bracmat you are running. <code>!w</code> and <code>!c</code> evaluate to sections 11 and 12 of the GPL. More vital is the variable <code>main</code>, which is the interpreter's main loop. Setting it to another value changes the behaviour of the interpreter. When running in interactive mode, <code>!</code> or <code>!""</code> evaluates to the last answer, so the empty string is the name of yet another special variable. These variables can be reassigned.
=={{header|C}}==
C99 introduced the (read-only) special variable <code>__func__</code> (of type <code>static const char[]</code>) which holds the name of the current function.
Furthermore one could consider <code>errno</code> from <code><errno.h></code> as a special variable although it actually is a macro which expands to an modifiable lvalue of type <code>int</code>. Many library functions set it to a positive value in case of an error.
=={{header|C++}}==
Besides <code>errno</code> like C, C++ has the <code>this</code> pointer so objects can refer to themselves.
<syntaxhighlight lang="cpp">#include <iostream>
struct SpecialVariables
{
int i = 0;
SpecialVariables& operator++()
{
// 'this' is a special variable that is a pointer to the current
// class instance. It can optionally be used to refer to elements
// of the class.
this->i++; // has the same meaning as 'i++'
// returning *this lets the object return a reference to itself
return *this;
}
};
int main()
{
SpecialVariables sv;
auto sv2 = ++sv; // makes a copy of sv after it was incremented
std::cout << " sv :" << sv.i << "\n sv2:" << sv2.i << "\n";
}</syntaxhighlight>
{{out}}
<pre>
sv :1
sv2:1
</pre>
=={{header|Clojure}}==
The following snippet prints a list of the special variables defined in clojure.core, in *earmuff* form. For further information, consult the [http://clojuredocs.org/quickref/shortdesc/Clojure%20Core documentation].
<syntaxhighlight lang="clojure">
(apply str (interpose " " (sort (filter #(.startsWith % "*") (map str (keys (ns-publics 'clojure.core)))))))
</syntaxhighlight>
{{Out}}
<pre>*1 *2 *3 *agent* *allow-unresolved-vars* *assert* *clojure-version* *command-line-args* *compile-files* *compile-path*
*compiler-options* *data-readers* *default-data-reader-fn* *e *err* *file* *flush-on-newline* *fn-loader* *in* *math-context*
*ns* *out* *print-dup* *print-length* *print-level* *print-meta* *print-readably* *read-eval* *source-path* *unchecked-math*
*use-context-classloader* *verbose-defrecords* *warn-on-reflection*</pre>
=={{header|Common Lisp}}==
Note: the term "special variable" has a meaning in Common Lisp and related dialects, different from the way it is being used here. It is a jargon which denotes a dynamically scoped variable. ANSI Common Lisp's standard-defined variables are special variables in both senses of the term.
The following code snippet prints a list of all 44 special variables defined by the Common Lisp standard. For further information about each of them consult the [http://www.lispworks.com/documentation/HyperSpec/Front/X_Alph_9.htm online documentation].
<syntaxhighlight lang="lisp">(defun special-variables ()
(flet ((special-var-p (s)
(and (char= (aref s 0) #\*)
(find-if-not (lambda (x) (char= x #\*)) s)
(char= (aref s (1- (length s))) #\*))))
(let ((lst '()))
(do-symbols (s (find-package 'cl))
(when (special-var-p (symbol-name s))
(push s lst)))
lst)))
(format t "~a~%" (sort (special-variables) #'string<))</syntaxhighlight>
{{Out}}
<pre>(*BREAK-ON-SIGNALS* *COMPILE-FILE-PATHNAME* *COMPILE-FILE-TRUENAME* *COMPILE-PRINT* *COMPILE-VERBOSE* *DEBUG-IO*
*DEBUGGER-HOOK* *DEFAULT-PATHNAME-DEFAULTS* *ERROR-OUTPUT* *FEATURES* *GENSYM-COUNTER* *LOAD-PATHNAME*
*LOAD-PRINT* *LOAD-TRUENAME* *LOAD-VERBOSE* *MACROEXPAND-HOOK* *MODULES* *PACKAGE* *PRINT-ARRAY* *PRINT-BASE*
*PRINT-CASE* *PRINT-CIRCLE* *PRINT-ESCAPE* *PRINT-GENSYM* *PRINT-LENGTH* *PRINT-LEVEL* *PRINT-LINES*
*PRINT-MISER-WIDTH* *PRINT-PPRINT-DISPATCH* *PRINT-PRETTY* *PRINT-RADIX* *PRINT-READABLY* *PRINT-RIGHT-MARGIN*
*QUERY-IO* *RANDOM-STATE* *READ-BASE* *READ-DEFAULT-FLOAT-FORMAT* *READ-EVAL* *READ-SUPPRESS* *READTABLE*
*STANDARD-INPUT* *STANDARD-OUTPUT* *TERMINAL-IO* *TRACE-OUTPUT*)</pre>
Inside the REPL, there are more special variables available:
* -: Contains the form that is currently evaluated.
<pre>> (format t "~a" -)
(FORMAT T ~a -)
NIL</pre>
* *, **, ***: Contain the last, penultimate, antepenultimate primary values that were printed.
<pre>> (+ 1 2)
3
> (values 1 2)
1 ;
2
> (* 4 5)
20
> (list * ** ***)
(20 1 3)</pre>
* +, ++, +++: Contain the last, penultimate, antepenultimate forms that were evaluated.
<pre>> (+ 1 2)
3
> (values 1 2)
1 ;
2
> (* 4 5)
20
> (list + ++ +++)
((* 4 5) (VALUES 1 2) (+ 1 2))</pre>
* /, //, ///: Contain a list of the last, penultimate, antepenultimate values that were printed.
<pre>> (floor 10 2)
5 ;
0
> (values 1 'a "foo")
1 ;
A ;
"foo"
> (+ 1 2)
3
> (list / // ///)
((3) (1 A "foo") (5 0))</pre>
=={{header|D}}==
In D there are not many special variables, beside a string[] argument of the main function. Variables like the C "errno" are usually not used, despite the C library is available.
One special boolean variable is __ctfe, that is read-only and it's true inside functions when they are evaluated at compile-time, and false otherwise.
=={{header|DWScript}}==
DWScript has no special variables in the base language.
Hosts can however define any number of contextual or environmental variables.
=={{header|Dyalect}}==
Dyalect has a special <code>this</code> which is available inside methods:
<syntaxhighlight lang="dyalect">func Integer.Double() {
this + this
}
print(8.Double())</syntaxhighlight>
=={{header|Déjà Vu}}==
Calls to some of the standard library functions can be optimized into certain opcodes or sequences of opcodes, namely:
<pre>set setglobal local get getlocal return recurse drop dup swap rot over
[] {} pop-from push-to push-through has get-from set-to raise reraise
call for pass</pre>
In addition, <code>eva</code> is special:
<syntaxhighlight lang="dejavu">!print "hey" #is really short for
eva!print "hey"</syntaxhighlight>
EVA is the part of the standard library that takes care of communication with the outside world. It makes extensive use of the method call syntax, unlike the rest of the standard library, that is why it is special.
=={{header|Erlang}}==
Erlang has no special variables.
What it does have are special functions, module_info/0 and module_info/1. These are added to a module automatically, without being present in the code.
<syntaxhighlight lang="erlang">
-module( special_variables ).
-export( [task/0] ).
task() -> ok.
</syntaxhighlight>
{{out}}
<pre>
2> special_variables:module_info().
[{exports,[{task,0},{module_info,0},{module_info,1}]},
{imports,[]},
{attributes,[{vsn,[11317586745549911665324094732832680475]}]},
{compile,[{options,[]},
{version,"4.8"},
{time,{2013,10,28,20,2,58}},
{source,"/Users/bengt/rosetta/special_variables.erl"}]}]
3> special_variables:module_info(exports).
[{task,0},{module_info,0},{module_info,1}]
</pre>
=={{header|Forth}}==
Line 363 ⟶ 683:
The DO-LOOP construct also has accessors '''I''' and '''J''' (and sometimes '''K''') for obtaining the loop indices of the inner and outer nested loops.
===Common Practice===
Although not mandated in the Forth language specification, traditionally the language implements system variables as what are called USER variables. The name dates back to the a time when FORTH was used as a multi-user O/S and therefore each user needed a set of variables to control the state of their instance of the system. The user variables exist in a memory block called the USER AREA and are replicated for each task. When used for embedded systems, Forth is commonly implemented as a multi-tasking system, so this architecture is still relevant today. On a context switch the system assigns a system VARIABLE called 'UP' (user pointer) to point to the new task's USER AREA. Using UP, the task's local stack pointers can be read into the machine and a fast context switch can be completed. UP is commonly held in a CPU register on machines that have larger register sets.
This following list is an example of a set of USER variables in a small system. Consult the implementation documents for details on the USER variables in a specific FORTH system.
<pre>Name Type Description
---------------------------------------------
TIB integer Terminal Input Buffer address
U0 integer current user area address
>IN integer holds offset into TIB, used for parsing
BASE integer holds number conversion radix
STATE integer holds compiler state (true=compiling, false=interpreting)
DP integer holds dictionary memory pointer
'SOURCE integer[2] contains length and address of input source
LATEST integer address of last word added to dictionary
HP integer HOLD pointer, used for number formatting routines
LP integer leave-stack pointer, used by do loops
S0 integer end of parameter stack
PAD chars[80] Generic buffer. (size is implementation dependent)
L0 integer bottom of leave stack
R0 integer end of return stack</pre>
It is worth noting that any of these variable names could be used in a program.
The result would be that the original variable would be hidden from the compiler as the new variable with the same name would be found first. In other words the function of the original variable would NOT change in system.
Forth has a "hyper-static" name space.
=={{header|Fortran}}==
Fortran offers no special variables such as Pi, e, etc. as a part of the language, not even the modern special floating-point "values" such as NaN. Indeed, the syntax has no reserved words generally so that <code>GO TO</code> could be the name of a variable without damage to GO TO statements, though it is generally agreed that calling a variable END is provocative... It does have some ''numbers'' that are special: 5 is the input/output "unit number" for keyboard input and 6 for output to "standard output", the screen on desktop computers; in the past there have been other values that were associated to devices such as the card reader, card punch, lineprinter, paper tape reader, and so on at any given installation. But these constants are not given names as mnemonics for their special values, except by the programmer. There is no equivalent of SYSOUT as in WRITE(SYSOUT,''etc'' without definition by the programmer.
Certain statements involve special names in what appear to be assignments of values to or from a special name that has a value just like a named variable does, but these are ''not'' proper variables at all. For instance, in <syntaxhighlight lang="fortran"> INQUIRE(FILE = FILENAME(1:L),EXIST = EXIST, !Here we go. Does the file exist?
1 ERR = 666,IOSTAT = IOSTAT) !Hopefully, named in good style, etc.
IF (EXIST) THEN !So, does the named file already exist?
...etc.</syntaxhighlight>
ERR is a special name, but only inside the context of the INQUIRE (and OPEN, and WRITE, ''etc.'') statement, it is not the name of an existing variable outside that statement whether defined by the language or by the programmer, and if the programmer were to define a variable called ERR it would have no relevance within that INQUIRE statement - though <code>ERR = ERR</code> ''would'' be workable if an ASSIGN statement had assigned statement label 666 to variable ERR. Similarly, the variable named FILENAME is declared by the programmer and because there are no reserved words, could be just FILE. Likewise, EXIST is declared (as LOGICAL) and IOSTAT (as INTEGER) as a mnemonic aid and also to save on the trouble of remembering whether the assignment works left-to-right or right-to-left in each case. It is right-to-left for FILE = ''filename'', input to the INQUIRE statement and left-to-right for EXIST = ''variable'', an output of the INQUIRE statement.
=={{header|FreeBASIC}}==
FreeBASIC has no 'special variables'.
=={{header|Go}}==
Go has no special variables in the base language.
A number of the standard packages however, define special variables or constants. Standard error values are common, as are enumeration-like constants for controling functions. Examples of some more frequently used package variables might be io.EOF, os.Args, and os.Stdout.
See also [[Topic variable#Go]] for an example of '.' of the template package.
=={{header|Haskell}}==
Like C, there are practically no special variables. The program entry point, main, is the one exception.
=={{header|Icon}} and {{header|Unicon}}==
Icon and Unicon have special variables known as keywords which are syntactically are preceded by an &.
<syntaxhighlight lang="unicon">
# &keyword # type returned(indicators) - brief description
# indicators:
Line 443 ⟶ 811:
&y # integer(=G) - pointer vertical position
# keywords may also fail if the corresponding feature is not present.
# Other variants of Icon (e.g. MT-Icon) will have different mixes of keywords.</
=={{header|IS-BASIC}}==
<syntaxhighlight lang="is-basic">BLACK - The code of colour black.
BLUE - The code of colour blue.
CYAN - The code of colour cyan.
DATE$ - The current date in the standard format.
EXLINE - The number of the last statement that caused an exception.
EXTYPE - The error code of the last exception.
FREE - The amount of memory free and avaible to the current program.
GREEN - The code of colour green.
INF - The largest positive number that the IS-BASIC can handle.
MAGENTA - The code of colour magenta.
PI - Value of the Pi. This is rounded to 3.141592654
RED - The code of colour red.
TIME$ - The current time in the standard format.
WHITE - The code of colour white.
YELLOW - The code of colour yellow.
VERNUM - Version number of the BASIC</syntaxhighlight>
=={{header|J}}==
Line 459 ⟶ 845:
Note that the result of an adverb or conjunction that uses either x or y and one of these other names is always a verb. In this case, x and/or y represent arguments passed to the derived verb.
Some examples:
<syntaxhighlight lang="j"> {{ y }} 1
1
1000 {{ x + y }} 1
1001
100 {{ m + y }} 1
101
(1000) 100 {{ x + m + y }} 1
1101
100 {{ m + n + y }} 10 (1)
111
(1000) 100 {{ x + m + n + y }} 10 (1)
1111
(1000) + {{ x u n u y }} 10 (1)
1011
(1000) 100 {{ x v m v y }} + (1)
1101</syntaxhighlight>
These names may be used as regular names, but that is bad practice except in the context of debugging or illustration.
Line 612 ⟶ 1,016:
tolist topara ucpboxdraw
unboxfkeys unboxskeys winmax </pre>
=={{header|Java}}==
Java is heavily object-oriented, and is mostly statically-typed. There aren't many special variables, or aggregates, similar to dynamically-typed languages.<br />
There is ''null'', which is used to represent an object which has no reference assigned.
<syntaxhighlight lang="java">
Object object = null
</syntaxhighlight>
There is ''true'' and ''false'' which are used to denote a ''Boolean'' value.
<syntaxhighlight lang="java">
boolean value = true
</syntaxhighlight>
There is the ''this'' and ''super'' variables, used to reference the current class and parent class, respectively.
<syntaxhighlight lang="java">
this.object
</syntaxhighlight>
<syntaxhighlight lang="java">
super(value)
</syntaxhighlight>
To avoid confusion to anyone unfamiliar with Java, there is the ability to import static, final, variables from other classes.<br />
While these are not 'special variables' they may appear that way to a new user.
<syntaxhighlight lang="java">
import static java.lang.Math.*;
</syntaxhighlight>
<syntaxhighlight lang="java">
double area = PI * (2 * 2);
</syntaxhighlight>
There is the first parameter of the ''main'' method, which is of type ''String[]''.<br />
It is non-null and includes any arguments depicted during execution.
<syntaxhighlight lang="java">
public static void main(String[] args)
</syntaxhighlight>
<br />
Additionally ...<br />
Java has only a few special variables. There is a <code>String</code>-Array for passing command-line-arguments to the program, and there is a <code>Class</code>-Object that can be accessed in a variable-like manner. It is used for reflection, (like examining and modifing class members, their type and modifiers during runtime).
There is the <code>System</code>-"Object" that contains various (mostly static) data about the enviroment the Java VM runs on, and it's cousin <code>Runtime</code> that provides data that is more prone to change during runtime, like available CPU cores and RAM.
Inside an object there is <code>this</code>, a reference that points to the object itself (like 127.0.0.1 in networking) and are used to qualify member access. There is also <code>super</code> that does the same for the base class (actually "the next class in the inheritance tree"). Both are not demonstrated in the example below.
<syntaxhighlight lang="java">import java.util.Arrays;
public class SpecialVariables {
public static void main(String[] args) {
//String-Array args contains the command line parameters passed to the program
//Note that the "Arrays.toString()"-call is just used for pretty-printing
System.out.println(Arrays.toString(args));
//<Classname>.class might qualify as a special variable, since it always contains a Class<T>-object that
//is used in Reflection
System.out.println(SpecialVariables.class);
//The following are not really "variables", since they are properly encapsulated:
//System.getenv() returns a String-String-Map of environment-variables
System.out.println(System.getenv());
//System.getProperties() returns a Map of "things somebody might want to know", including OS and architecture
// the Java VM runs on, various paths like home direcoty of the user that runs the program, class (library) paths,
System.out.println(System.getProperties());
//Runtime.getRuntime() returns a Runtime-Object that contains "changing" data about the running Java VM's
// environment, like available processor cores or available RAM
System.out.println(Runtime.getRuntime().availableProcessors());
}
}
</syntaxhighlight>
=={{header|JavaScript}}==
<code>this</code> evaluates to the object the immediately enclosing function was called on as a method, if it was. If it was not called as a method, <code>this</code> is either the global environment object (usually <code>window</code> in browsers) in non-strict mode, or <code>undefined</code> in strict mode. <code>this</code> is an expression resembling a variable, but not actually a variable; for example, it is a syntax error to assign to it.
<syntaxhighlight lang="javascript">var obj = {
foo: 1,
bar: function () { return this.foo; }
};
obj.bar(); // returns 1</syntaxhighlight>
When a function is entered, the ''variable'' <code>arguments</code> is bound to an “arguments object” which is an array-like object containing the function's arguments, as well as some other information. This how [[varargs]] functions are implemented in JavaScript. If the function's parameters contain “<code>arguments</code>” explicitly, then it is ''not'' overridden and functions as an ordinary parameter.
<syntaxhighlight lang="javascript">function concat() {
var s = "";
for (var i = 0; i < arguments.length; i++) {
s += arguments[i];
}
return s;
}
concat("a", "b", "c"); // returns "abc"</syntaxhighlight>
=={{header|jq}}==
Variables in jq are identifiers preceded by the sigil "$", e.g. <code>$x</code>. There are no predefined variables, but jq does allow variables to be assigned string values on the command line.
For example:<syntaxhighlight lang="sh">$ jq -n -M --arg x 1 '$x|type' # (*)
"string"</syntaxhighlight>
(*) Windows users would write "$x|type".
=={{header|Julia}}==
Julia starts with the <code>Base</code> module loaded. Taking "special variables" to mean names in the default global namespace (<code>Base</code>) that aren't functions, types, or modules, then you can obtain them with
<syntaxhighlight lang="julia">join(sort(filter(sym -> let n=eval(sym); !(isa(n, Function) || isa(n, Type) || isa(n, Module)); end, names(Base))), ", ")</syntaxhighlight>
{{out}}
<pre>":, ARGS, CPU_CORES, C_NULL, DL_LOAD_PATH, DevNull, ENDIAN_BOM, ENV, I, Inf, Inf16, Inf32, InsertionSort, JULIA_HOME, LOAD_PATH, MS_ASYNC, MS_INVALIDATE, MS_SYNC, MergeSort, NaN, NaN16, NaN32, OS_NAME, QuickSort, RTLD_DEEPBIND, RTLD_FIRST, RTLD_GLOBAL, RTLD_LAZY, RTLD_LOCAL, RTLD_NODELETE, RTLD_NOLOAD, RTLD_NOW, RoundDown, RoundFromZero, RoundNearest, RoundToZero, RoundUp, STDERR, STDIN, STDOUT, VERSION, WORD_SIZE, catalan, cglobal, e, eu, eulergamma, golden, im, pi, γ, π, φ"</pre>
(Because of Julia's multiple dispatch that allows a single function to have multiple definitions for different argument types, combined with the ability of functions in modules or variables in the local scope to safely shadow names in the global namespace, having a large global namespace is seen as a convenience rather than a problem.)
=={{header|Kotlin}}==
There are two 'special variables' that I can think of in Kotlin:
* 'it' which implicitly refers to the parameter of a lambda expression where it only has one.
* 'field' which implicitly refers to the backing field of a property within its get/set accessors.
The following program illustrates their usage:
<syntaxhighlight lang="scala">// version 1.0.6
class President(val name: String) {
var age: Int = 0
set(value) {
if (value in 0..125) field = value // assigning to backing field here
else throw IllegalArgumentException("$name's age must be between 0 and 125")
}
}
fun main(args: Array<String>) {
val pres = President("Donald")
pres.age = 69
val pres2 = President("Jimmy")
pres2.age = 91
val presidents = mutableListOf(pres, pres2)
presidents.forEach {
it.age++ // 'it' is implicit sole parameter of lambda expression
println("President ${it.name}'s age is currently ${it.age}")
}
println()
val pres3 = President("Theodore")
pres3.age = 158
}</syntaxhighlight>
{{out}}
<pre>
President Donald's age is currently 70
President Jimmy's age is currently 92
Exception in thread "main" java.lang.IllegalArgumentException: Theodore's age must be between 0 and 125
at President.setAge(test10.kt:5)
at Test10Kt.main(test10.kt:21)
</pre>
=={{header|Lasso}}==
In Lasso parameters can be referenced as numerical locals within methods or unbound captures. [http://lassoguide.com/language/variables.html?#parameter-pseudo-locals]
<syntaxhighlight lang="lasso">{return #1 + ':'+#2}('a','b') // a:b</syntaxhighlight>
<syntaxhighlight lang="lasso">define test(a,b) => #1+':'+#2
test('y','z') // y:z</syntaxhighlight>
=={{header|Lingo}}==
In terms of statement "put <varName>" showing some meaningful output, the following can be rated as "special variables" in Lingo:
-- constants
*BACKSPACE
*EMPTY
*ENTER
*FALSE
*PI
*QUOTE
*RETURN
*SPACE
*TAB
*TRUE
*VOID
<br />
-- core objects
*_global
*_key
*_mouse
*_movie
*_player
*_system
=={{header|LiveCode}}==
The most important special variable is known as ''it''. The LC Dictionary says "A special local variable that is used with commands such as get, read from file, convert, ask, and answer. Use the it keyword to get the result of certain commands, or as a handy temporary storage place." It's use is closely followed by a special function called ''result'' that is similarly mentioned in the dictionary as well "Is a global property returning the last value returned by return from a handler, from an engine function, or from an engine command which sets the result."
Further to those, LiveCode comes with a plethora of built-in constants, which are readily listed with the following command:
<syntaxhighlight lang="livecode">put the constantNames</syntaxhighlight>It also provides colours as built-ins, accessible through <syntaxhighlight lang="livecode">the colornames</syntaxhighlight> You can search the dictionary in the IDE using text "names" to discover more such as the ''propertyNames'' & the ''commandNames'', though are not strictly pertinent to this task.
=={{header|Lua}}==
; arg : global table containing command line parameters with the name of the program at index 0. Not available in interactive mode
; _G : the table with the ''global environment'', i.e. all global variables, including itself and the other variables listed here
; _VERSION : string with the name of the interpreter and the major and minor version, e.g. "Lua 5.2"
To list all global variables:
<syntaxhighlight lang="lua">for n in pairs(_G) do print(n) end</syntaxhighlight>
The list will include built-in global functions, whose availability depends on the implementation and compile time configuration.
=={{header|M2000 Interpreter}}==
There some read only variables. We can use Help dir$ to get help about dir$.
All identifiers can be change to be used as variables, using a dot. For modules/functions in a group we have to define these variables using a dot.
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
Let inkey$="hello", dir$="Something Else"
\\ using a dot we tell to interpreter to skip internal identifiers,
\\ and look for user variables
Print .inkey$="hello", .dir$="Something Else"
Print dir$ ' return current path
do
Print "wait to press space"
Until inkey$=" "
}
Checkit
Module check2 {
Global inkey$="ok"
Print .inkey$="ok"
}
check2
Module Check3 {
Group A {
Module Check3 {
\\ using a dot before the name
.inkey$="ok"
Print .inkey$="ok"
}
}
A.Check3
}
Check3
</syntaxhighlight>
<pre>
about$, appdir$, browser$, clipboard$, clipboard.image$, codepage, colors,
command$, computer$, control$, dir$, duration, empty, error$, field,
fontname$, grabframe$, height, hwnd, inkey$, islet, isnum, key$, lan$,
letter$, memory, menu.visible, menu, menuitems, mode, module$, monitor.stack,
monitor.stack.size, motion.wx, motion.wy, motion.x, motion.xw, motion.y, motion.yw,
mouse, mouse.key, mouse.x, mouse.y, mousea.x, mousea.y, movie.counter, movie.device$,
movie.error$, movie.status$, movie, music.counter, now, number, os$, osbit, parameters$,
pen, platform$, point, pos, pos.x, pos.y, printername$, properties$, reportlines, rnd,
row, scale.x, scale.y, speech, sprite$, stack.size, tab, tempname$, temporary$,
this, threads$, tick, timecount, today, twipsx, twipsy, user.name$, volume,
width, x.twips, y.twips
</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">Grid[Partition[Names["$*"],4]]
->
$Aborted $ActivationGroupID $ActivationKey $ActivationUserRegistered
$AddOnsDirectory $AllowDataUpdates $AllowDocumentationUpdates $AllowInternet
$AssertFunction $Assumptions $BaseDirectory $BatchInput
$BatchOutput $BoxForms $ByteOrdering $Canceled
$CharacterEncoding $CharacterEncodings $CommandLine $CompilationTarget
$ConditionHold $ConfiguredKernels $Context $ContextPath
$ControlActiveSetting $CreationDate $CurrentLink $DateStringFormat
$DefaultFont $DefaultFrontEnd $DefaultImagingDevice $DefaultPath
$Display $DisplayFunction $DistributedContexts $DynamicEvaluation
$Echo $Epilog $ExportFormats $Failed
$FinancialDataSource $FormatType $FrontEnd $FrontEndSession
$GeoLocation $HistoryLength $HomeDirectory $IgnoreEOF
$ImagingDevices $ImportFormats $InitialDirectory $Input
$InputFileName $Inspector $InstallationDate $InstallationDirectory
$InstalledServices $InterfaceEnvironment $InternetProxyRules $IterationLimit
$KernelCount $KernelID $Language $LaunchDirectory
$LibraryPath $LicenseExpirationDate $LicenseID $LicenseProcesses
$LicenseServer $LicenseSubprocesses $LicenseType $Line
$Linked $LinkSupported $LoadedFiles $MachineAddresses
$MachineDomain $MachineDomains $MachineEpsilon $MachineID
$MachineName $MachinePrecision $MachineType $MaxExtraPrecision
$MaxLicenseProcesses $MaxLicenseSubprocesses $MaxMachineNumber $MaxNumber
$MaxPiecewiseCases $MaxPrecision $MaxRootDegree $MessageGroups
$MessageList $MessagePrePrint $Messages $MinMachineNumber
$MinNumber $MinorReleaseNumber $MinPrecision $ModuleNumber
$NetworkLicense $NewMessage $NewSymbol $Notebooks
$NumberMarks $Off $OperatingSystem $Output
$OutputForms $OutputSizeLimit $Packages $PacletSite
$ParentLink $ParentProcessID $PasswordFile $PatchLevelID
$Path $PathnameSeparator $PerformanceGoal $PipeSupported
$Post $Pre $PreferencesDirectory $PrePrint
$PreRead $PrintForms $PrintLiteral $PrintServiceRequest
$PrintServiceResponse $PrintShortErrorMessages $PrintWSDLDebug $ProcessID
$ProcessorCount $ProcessorType $ProductInformation $ProgramName
$RandomState $RecursionLimit $ReleaseNumber $RootDirectory
$ScheduledTask $ScriptCommandLine $SessionID $SetParentLink
$SharedFunctions $SharedVariables $SoundDisplay $SoundDisplayFunction
$SuppressInputFormHeads $SynchronousEvaluation $SyntaxHandler $System
$SystemCharacterEncoding $SystemID $SystemWordLength $TemporaryDirectory
$TemporaryPrefix $TextStyle $TimedOut $TimeUnit
$TimeZone $TopDirectory $TraceOff $TraceOn
$TracePattern $TracePostAction $TracePreAction $Urgent
$UserAddOnsDirectory $UserBaseDirectory $UserBasePacletsDirectory $UserDocumentsDirectory</syntaxhighlight>
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">/* There are many special variables in Maxima: more than 250 are used for options, for example */
fpprec; /* precision for big floats */
obase; /* number base for output */
/* Other variables are read-only, and give the list of user-defined variables, functions... */
infolists; /* give the names of all available lists */
[labels, values, functions, macros, arrays, myoptions, props, aliases, rules, gradefs, dependencies, let_rule_packages, structures]</syntaxhighlight>
=={{header|MIPS Assembly}}==
When multiplying two registers, the product is always stored in the <code>$HI</code> and <code>$LO</code> registers. Their contents can be read into your standard registers with the commands <code>mfhi $reg</code> and <code>mflo $reg</code>.
<syntaxhighlight lang="mips">
li $t0,0x4500
li $t1,0xFFFF
multu $t0,$t1 ;unsigned multiplication of $t0 and $t1
mfhi $t0 ;load the top 32 bits of the product into $t0
mflo $t1 ;load the bottom 32 bits of the product into $t1</syntaxhighlight>
Division is a similar story, except <code>$HI</code> holds the remainder and <code>$LO</code> holds the quotient.
When using <code>JAL functionName</code> to call a function, the <code>$ra</code> register holds the return address.
=={{header|ML/I}}==
===Input===
<syntaxhighlight lang="ml/i">MCSKIP "WITH" NL
"" Special variables
"" There are four different kinds of variables in ML/I.
"" Permanent (P) variables - these have no special predefined values.
"" Character (C) variables - these have no special predefined values.
"" Temporary (T) variables - a macro has at least three of these, and
"" those have predefined values.
"" System (S) variables - these are for control and status. The number
"" of these is implementation dependent.
MCSKIP MT,<>
MCINS %.
MCDEF TVARDEMO , NL
AS <T-variables are local to the current macro call
T1 is the number of arguments to current macro call - value is %T1.
T2 is the number of macro calls so far - value is %T2.
T3 is the current depth of nesting - value is %T3.
>
TVARDEMO xxx,yyy
MCDEF SVARDEMO WITHS NL
AS <The first nine S-variables are implementation independent
S1 controls startline insertion - value is %S1.
S2 is the current source text line number - value is %S2.
S3 controls error messages related to warning markers - value is %S3.
S4 controls context printout after a <MCNOTE> - value is %S4.
S5 is the count of processing errors - value is %S5.
S6 enables the definition of an atom to be changed - value is %S6.
S7, S8 and S9 are currently unused.
All other S-variables have implementation defined meanings.
>
SVARDEMO</syntaxhighlight>
===Output===
<syntaxhighlight lang="ml/i">T-variables are local to the current macro call
T1 is the number of arguments to current macro call - value is 2
T2 is the number of macro calls so far - value is 5
T3 is the current depth of nesting - value is 1
The first nine S-variables are implementation independent
S1 controls startline insertion - value is 0
S2 is the current source text line number - value is 32
S3 controls error messages related to warning markers - value is 0
S4 controls context printout after a MCNOTE - value is 0
S5 is the count of processing errors - value is 0
S6 enables the definition of an atom to be changed - value is -1
S7, S8 and S9 are currently unused.
All other S-variables have implementation defined meanings.</syntaxhighlight>
=={{header|Nanoquery}}==
Nanoquery has a number of immutable special variables which can be listed by executing the following program:
<syntaxhighlight lang="nanoquery">println dumpstack()</syntaxhighlight>
{{out}}
<pre>{{dbsize, 0}, {col, 1}, {workingdir, C:\Users\Will\Programs\Nanoquery}, {false, false}, {interactive, false}, {main, true}, {packages, [, Nanoquery.Objects, Nanoquery.Exceptions]}, {libpath, C:\Users\Will\Programs\Nanoquery\nanoquery-2.3_1866}, {args, [-b, rosetta-code/specialvars.nq]}, {rec, 1}, {filename, }, {null, null}, {__file__, C:\Users\Will\Programs\Nanoquery\rosetta-code\specialvars.nq}, {true, true}, {prompt, [\S | rec\R col\C] % }, {cols, 0}, {lockedfiles, []}, {__calls__, [<global>:1]}}</pre>
These variables are:
<pre>dbsize: the amount of rows in the currently referenced database object
col: the index of the currently referenced database column
workingdir: the current working directory as a string
false: the boolean value false
interactive: a boolean that represents if this program is being run from the
interpreter interactively
main: boolean that represents if this code is in the global portion
of the current program
packages: list of strings holding the built-in packages that have been imported
libpath: string representing the path where the standard library is expected to be
args: list of string containing the args that the current program was
started with
rec: the index of the currently referenced database row
filename: the path of the currently open database file
null: represents the null object
__file__: absolute path of the current running program
true: the boolean value true
prompt: contains the current interpreter prompt string
cols: the amount of columns in the currently referenced database object
lockedfiles: list of strings containing the paths of files that have been locked
for writing by the 'lock' command
__calls__: stack containing the current Nanoquery call stack</pre>
=={{header|NetRexx}}==
For convenience, NetRexx provides some special names for naming commonly-used concepts within terms. These are only recognized if there is no variable of the same name previously seen in the current scope.
The current set of special names includes:
<code>'''ask''', '''class''', '''digits''', '''form''', '''length''', '''null''', '''source''', '''sourceline''', '''super''', '''this''', '''trace''', '''version'''</code>.
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols binary
class RCSpecialVariables
method RCSpecialVariables()
x = super.toString
y = this.toString
say '<super>'x'</super>'
say '<this>'y'</this>'
say '<class>'RCSpecialVariables.class'</class>'
say '<digits>'digits'</digits>'
say '<form>'form'</form>'
say '<[1, 2, 3].length>'
say [1, 2, 3].length
say '</[1, 2, 3].length>'
say '<null>'
say null
say '</null>'
say '<source>'source'</source>'
say '<sourceline>'sourceline'</sourceline>'
say '<trace>'trace'</trace>'
say '<version>'version'</version>'
say 'Type an answer:'
say '<ask>'ask'</ask>'
return
method main(args = String[]) public static
RCSpecialVariables()
return
</syntaxhighlight>
;Output
<pre>
<super>RCSpecialVariables@3487a5cc</super>
<this>RCSpecialVariables@3487a5cc</this>
<class>class RCSpecialVariables</class>
<digits>9</digits>
<form>scientific</form>
<[1, 2, 3].length>
3
</[1, 2, 3].length>
<null>
</null>
<source>Java method RCSpecialVariables.nrx</source>
<sourceline>21</sourceline>
<trace>off</trace>
<version>NetRexx 3.00 11 Jun 2011</version>
Type an answer:
answer
<ask>answer</ask>
</pre>
=={{header|Nim}}==
In Nim, there is only one special variable, named <code>result</code>. It is implicitly declared in procedure which returns a result and is initialized with binary zeroes. Statement <code>return value</code> is in fact a shortcut for:
<syntaxhighlight lang="nim">result = value
return</syntaxhighlight>
There are also variables declared in modules and exported. As some modules are implicitly imported, their exported variables are automatically visible. Modules implicitly imported are: “system” (which imports “iterators”, “assertions”, “dollars”, “io” and “widestr”), “threads” and “channels”, the latter two being activated if option <code>--thread:on</code> is used.
These implicit imports add these variables to the list of visible objects:
:– some hooks and handlers used in system programming: <code>globalRaiseHook</code>, <code>localRaiseHook</code>, <code>outOfMemHook</code>, <code>unhandledExceptionHook</code>, <code>errorMessageWriter</code>, <code>onUnhandledException</code>;
:– a read-only variable, <code>nimvm</code> which is true in Nim VM context and false otherwise;
:– the three standard files: <code>stdin</code>, <code>stdout</code>, <code>stderr</code>.
=={{header|OASYS}}==
The only special variable is <tt>player</tt> (of type <tt>object</tt>) which specifies which object the player invokes methods on by default.
=={{header|OASYS Assembler}}==
The only special variable is <tt>%@</tt> which specifies which object the player invokes methods on by default.
=={{header|OCaml}}==
Some predefined variables from the <code>[http://caml.inria.fr/pub/docs/manual-ocaml/libref/Sys.html Sys]</code> module:
<syntaxhighlight lang="ocaml">val argv : string array
(** The command line arguments given to the process.
The first element is the command name used to invoke the program.
The following elements are the command-line arguments
given to the program. *)
val executable_name : string
(** The name of the file containing the executable currently running. *)
val interactive : bool ref
(** This reference is initially set to [false] in standalone
programs and to [true] if the code is being executed under
the interactive toplevel system [ocaml]. *)
val os_type : string
(** Operating system currently executing the Caml program. One of
- ["Unix"] (for all Unix versions, including Linux and Mac OS X),
- ["Win32"] (for MS-Windows, OCaml compiled with MSVC++ or Mingw),
- ["Cygwin"] (for MS-Windows, OCaml compiled with Cygwin). *)
val word_size : int
(** Size of one word on the machine currently executing the Caml
program, in bits: 32 or 64. *)
val max_string_length : int
(** Maximum length of a string. *)
val max_array_length : int
(** Maximum length of a normal array. The maximum length of a float
array is [max_array_length/2] on 32-bit machines and
[max_array_length] on 64-bit machines. *)
val ocaml_version : string
(** [ocaml_version] is the version of Objective Caml.
It is a string of the form ["major.minor[.patchlevel][+additional-info]"],
where [major], [minor], and [patchlevel] are integers, and
[additional-info] is an arbitrary string. The [[.patchlevel]] and
[[+additional-info]] parts may be absent. *)</syntaxhighlight>
Some predefined variables from the <code>[http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html Pervasives]</code> module:
<syntaxhighlight lang="ocaml">val max_int : int
(** The greatest representable integer. *)
val min_int : int
(** The smallest representable integer. *)
val max_float : float
(** The largest positive finite value of type [float]. *)
val min_float : float
(** The smallest positive, non-zero, non-denormalized value of type [float]. *)
val epsilon_float : float
(** The difference between [1.0] and the smallest exactly representable
floating-point number greater than [1.0]. *)</syntaxhighlight>
=={{header|Oforth}}==
Oforth special variables are read-only :
{{out}}
<pre>
true
false
null
System.Out
System.In
System.Err
System.Console
System.Args
Systel.NbCores
System.CELLSIZE
System.VERSION
SYstem.MAXTHREADS
System.ASSERTMODE
System.ISWIN
System.ISLUNIX
</pre>
=={{header|Pascal}}==
Pascal does not have any predefined special variables.
However, two identifiers ''can'' become “special”:
If you list in the <tt>program</tt> parameter list the identifiers of the spelling <tt>input</tt> and/or <tt>output</tt>, they will identify <tt>text</tt> variables referring to an implementation-defined input and output facility.
<syntaxhighlight lang="pascal">program foo(input, output);
begin
{ In this program, `input` and `output` have special meaning. }
end.</syntaxhighlight>
Neverthless, these identifiers are in no way ''reserved''.
<syntaxhighlight lang="pascal">program foo(output);
var
input: integer;
begin
{ In this program only `output` has special meaning. }
end.</syntaxhighlight>
Note that some run-time libraries of compilers usually ship a variety of predefined variables, but these are not part of the programming language itself.
=={{header|PascalABC.NET}}==
Result is a special variable for the result of a function
<syntaxhighlight lang="delphi">
function Add(a,b: integer): integer;
begin
Result := a + b
end;
</syntaxhighlight>
Self is a special variable defined in every non-static method of a class. It is a reference to the current object
<syntaxhighlight lang="delphi">
type A = class
n: integer;
constructor (n: integer);
begin
Self.n := n
end;
end;
</syntaxhighlight>
value is a special variable defined in setter of a property. This is a value which is assigned in a right part of an assignment
<syntaxhighlight lang="delphi">
type A = class
n: integer;
property pn: integer write n := value;
end;
</syntaxhighlight>
=={{header|PARI/GP}}==
Line 628 ⟶ 1,654:
* <code>PARI_SIGINT_pending</code>: When this is nonzero, a SIGINT has been blocked but not yet handled.
=={{header|Perl
{{Works with|Perl 5.28}}
A selection of the variables with special meaning to Perl. If you find it hard to remember the 'punctuation' names, longer 'English' names are available via a core module.
<pre>use English; # enables use of long variable names
$. $INPUT_LINE_NUMBER # sequence number
$, $OUTPUT_FIELD_SEPARATOR # output field separator
$; $SUBSCRIPT_SEPARATOR # subscript separator for multidimensional array emulation
$_ $ARG # topic/current/default variable
$" $LIST_SEPARATOR # alternative output field separator
$+ $LAST_PAREN_MATCH # last substring matched to a regular expression subpattern
$0 $PROGRAM_NAME # name of the program being executed
$! $ERRNO # error number from host operating system
$@ $EVAL_ERROR # error from the last "eval" operator
$/ $INPUT_RECORD_SEPARATOR # input record separator
$\ $OUTPUT_RECORD_SEPARATOR # output record separator for 'print'
$| $OUTPUT_AUTOFLUSH # controls output buffering
$& $MATCH # string matched by last regular expression
$' $POSTMATCH # substring following last matched regular expression
$` $PREMATCH # substring preceding last matched regular expression
@ARGV # array containing the command line parameters
@F # array of fields of each line read in when auto-split is on
@INC # array of library search paths
%ENV # associative container holding the environment variables
%SIG # associative container holding signal handlers</pre>
=={{header|Phix}}==
{{libheader|Phix/basics}}
Phix has no special variables.
=={{header|PicoLisp}}==
Line 728 ⟶ 1,698:
- Class variables may be indicated by an upper case letter</pre>
For historical reasons, the global constant symbols 'T' and 'NIL' do not obey these rules, and are written in upper case.
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
Special variables in PL/I are termed "Pseudo-variables".
They are used only on the LHS of an assignment statement.
They include:
REAL to assign the real part of a COMPLEX variable;
IMAG to assign the imaginary part of a COMPLEX variable;
SUBSTR is used to assign part of a string (used on the LHS of an assignment);
STRING when used on the left-hand of an assignment;
UNSPEC used to assign a bit pattern to a variable;
ENTRYADDR is used to assign an address to an ENTRY variable that is
to be invoked;
ONCHAR resets the current value of the CHAR built-in function (when
a data conversion error occurs, and it is desired to re-attempt
the conversion);
ONSOURCE assigns a new value to the ONSOURCE built-in function
(may be used when a data conversion error occurs,
and a re-try of the conversion is to be attempted with modified data);
ONGSOURCE assigns a new value to the ONGSOURCE built-in function
(may be used when a data conversion error occurs,
and may be used when a re-try of the conversion is to be
attempted with modified data).
</syntaxhighlight>
=={{header|PowerShell}}==
This is the list:
<syntaxhighlight lang="powershell">
<#
$$
$?
$^
$_
$Args
$ConsoleFileName
$Error
$Event
$EventSubscriber
$ExecutionContext
$False
$ForEach
$Home
$Host
$Input
$LastExitCode
$Matches
$MyInvocation
$NestedPromptLevel
$NULL
$PID
$Profile
$PSBoundParameters
$PsCmdlet
$PsCulture
$PSDebugContext
$PsHome
$PSitem
$PSScriptRoot
$PsUICulture
$PsVersionTable
$Pwd
$Sender
$ShellID
$SourceArgs
$SourceEventArgs
$This
$True
#>
</syntaxhighlight>
For descriptions:
<syntaxhighlight lang="powershell">
help about_automatic_variables
</syntaxhighlight>
=={{header|PureBasic}}==
Line 734 ⟶ 1,778:
=={{header|Python}}==
By default, Python starts execution in a namespace which has direct access to names defined in the globals() dict and the __builtins__ dict. The members of which can be found by the following code:
<
print( '\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) )</
;Output
<pre>ArithmeticError AssertionError AttributeError BaseException BufferError BytesWarning DeprecationWarning EOFError
Line 754 ⟶ 1,798:
round set setattr slice sorted staticmethod str sum
super tuple type vars zip</pre>
=={{header|Quackery}}==
The trite answer would be that Quackery has no variables.
It does, however, have Ancillary Stacks which stand in for variables, in that they are places where values can reside. Their behaviour is to place a pointer to themselves on the stack (''the stack'' refers to the Quackery Data Stack, the place from which words take arguments and return results), so that they can have values moved to and from them.
Ancillary Stacks might also, arguably, be considered slightly outside the language proper. To use a metaphor, if Quackery is a workshop, and Quackery words are tools for working on data, then the stack is the workbench that data resides on while it is being worked upon, and Ancillary Stacks are the storage spaces where one can put things to keep the workbench tidy. If asked to list the tools in a workshop, would you necessarily list shelves and cupboards as tools?
If predefined system constants are to be included, (i.e. words that take no arguments and always return the same value, a category which includes Ancillary Stacks) then there are several, including but not limited to <code>space</code> which returns 32, <code>carriage</code> which returns 13 (and is taken to mean whatever the host system regards as a carriage return/line feed), <code>[]</code>, which returns the empty nest <code>[ ]</code>, <code>true</code> which returns 1 and <code>false</code> which returns 0.
However, I suspect the most useful answer is "those things which need to be taken into consideration whilst coding in Quackery, because they give words side-effects rather than the words being purely functional in their behaviour."
With this definition there is only one word that requires mention; <code>base</code>. <code>base</code> is a system ancillary stack that holds the current base for numerical i/o and converting numerical strings to and from numbers and so forth. It has a default value of 10 — i.e. Quackery regards numbers as decimal unless that assumption is overridden by putting a different value on the top of the ancillary stack called <code>base</code>.
=={{header|Racket}}==
Racket does not have special variables in the usual sense. In fact,
being a language that specializes in making up langugaes it has no
special anything hard-wired in.
But it does have "parameters" -- a kind of mutable values that can be
set for a specific dynamic runtime extent: either around some piece of
code, or globally, or in some thread. These parameters are used to
configure many aspects of the runtime system, for
example "current-directory" has the obvious meaning. (But again, the
names that are bound to these parameters are not special, and can be
changed or hidden.)
=={{header|Raku}}==
(formerly Perl 6)
It is probably useful to briefly explain normal variables in Raku before tackling special variables.
Variables in Raku have a prefix sigil to distinguish them from named subroutines, functions, classes, and so on. There is a system of sigils to mark the fundamental structural type of the variable:
<syntaxhighlight lang="raku" line> $foo scalar (object)
@foo ordered array
%foo unordered hash (associative array)
&foo code/rule/token/regex
::foo package/module/class/role/subset/enum/type/grammar</syntaxhighlight>
Sigils indicate overall interface, not the exact type of the bound object. Different sigils imply different minimal abilities. Ordinary sigils indicate normally scoped variables, either lexical or package scoped. Oddly scoped variables include a secondary sigil (a twigil) that indicates what kind of strange scoping the variable is subject to:
<syntaxhighlight lang="raku" line> $foo # ordinary scoping
$.foo # object attribute public accessor
$^foo # self-declared formal positional parameter
$:foo # self-declared formal named parameter
$*foo # dynamically overridable global variable
$?foo # compiler hint variable
$=foo # POD variable
$<foo> # match variable, short for $/{'foo'}
$!foo # object attribute private storage
$~foo # the foo sublanguage seen by the parser at this lexical spot</syntaxhighlight>
A selection (not comprehensive) of Raku's automatically set and/or pre-defined compile-time and run-time variables.
<syntaxhighlight lang="raku" line># Lexical variables
$_ # implicit variable lexically scoped to the current block
$! # current Exception object
$/ # last match
$0, $1, $2... # captured values from match: $/[0], $/[1], $/[2] ...
# Compile-time variables
$?PACKAGE # current package
$?CLASS # current class
$?MODULE # current module
$?ROLE # current role
$?DISTRIBUTION # which OS distribution am I compiling under
$?FILE # current filename of source file
$?LINE # current line number in source file
&?ROUTINE # current sub or method (itself)
&?BLOCK # current block (itself)
# Dynamic variables
$*USAGE # value of the auto-generated USAGE message
$*PROGRAM-NAME # path to the current executable
$*PROGRAM # location (in the form of an IO::Path object) of the Raku program being executed
@*ARGS # command-line arguments
$*ARGFILES # the magic command-line input handle
$*CWD # current working directory
$*DISTRO # which OS distribution am I running under
%*ENV # system environment variables
$*ERR # standard error handle
$*EXECUTABLE-NAME # name of the Raku executable that is currently running
$*EXECUTABLE # IO::Path absolute path of the Raku executable that is currently running
$*IN # standard input handle; is an IO object
$*KERNEL # operating system running under
$*OUT # standard output handle
$*RAKU # Raku version running under
$*PID # system process id
$*TZ # local time zone
$*USER # system user id
# Run-time variables
$*COLLATION # object that can be used to configure Unicode collation levels
$*TOLERANCE # used by the =~= operator to decide if two values are approximately equal
$*DEFAULT-READ-ELEMS # affects the number of bytes read by default by IO::Handle.read</syntaxhighlight>
Also, not really a variable but...
<syntaxhighlight lang="raku" line> * # A standalone term that has no fixed value, instead it captures the notion of "Whatever",
# the meaning of which is decided lazily by whatever it is an argument to.
# See the docs on Whatever: https://docs.raku.org/type/Whatever</syntaxhighlight>
=={{header|REXX}}==
===version 1===
The REXX language has three special variables:
:::* '''RC''' [the '''r'''eturn '''c'''ode from commands issued to the host]
:::* '''RESULT''' [the result '''RETURN'''ed from a subroutine or function]
:::* '''SIGL''' [the source line number that did the transfer of control]
Each of the above may be used as a regular REXX variable; they aren't reserved keywords or reserved variable names.
<br>Because REXX may define (or re-define) any of these variables during execution of the REXX program, its recommended that they be not be used as regular REXX variables.
Initially, the above three special variables aren't defined (until the appropriate action for their use has been performed).
: If no commands have been issued to the host, then the '''RC''' special variable isn't defined.
: If no subroutines have been invoked, then the '''RESULT''' special variable isn't defined.
: If no SIGNAL or CALL (or subroutine invocation) has been used, then the '''SIGL''' special variable isn't defined.
:::: (This excludes the use of:
:::::::* '''SIGNAL ON ααα'''
:::::::* '''SIGNAL OFF ααα'''
:::: which don't actually transfer control.)
In each case, the three special variable names ('''RC''', '''RESULT''', and '''SIGL''') may be in lower/upper/mixed case.
<br><br>The scope of the special variables is LOCAL.
<syntaxhighlight lang="rexx">/*REXX program demonstrates REXX special variables: RC, RESULT, SIGL */
/*line two. */
/*line three.*/ say copies('═',79)
rc=1/3 /*line four. */
signal youWho /*line five. */
myLoo='this got skipped' /*line six. */
youwho: /*line seven.*/
sep=copies('─', 9) /*line eight.*/
say sep 'SIGL=' sigl /*line nine. */
say sep 'REXX source statement' SIGL '=' sourceline(sigl)
say copies('═',79)
g=44
call halve g
say sep 'rc=' rc
say sep 'result=' result
say copies('═',79)
h=66
hh=halve(h)
say sep 'rc=' rc
say sep 'result=' result
say sep 'hh=' hh
say copies('═',79)
'DIR /ad /b' /*display the directories (Bare).*/
say sep 'rc=' rc
say sep 'result=' result
say copies('═',79)
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────HALVE subroutine────────────────────*/
halve: return arg(1) / 2 /*a simple halving function. */</syntaxhighlight>
'''output''' using:
:::* Regina REXX
<pre>
═══════════════════════════════════════════════════════════════════════════════
───────── SIGL= 5
───────── REXX source statement 5 = signal youWho /*line five. */
═══════════════════════════════════════════════════════════════════════════════
───────── rc= 0.333333333
───────── result= 22
═══════════════════════════════════════════════════════════════════════════════
───────── rc= 0.333333333
───────── result= 22
───────── hh= 33
═══════════════════════════════════════════════════════════════════════════════
Documents and Settings
Program Files
Recycled
System Volume Information
TEMP
WINDOWS
───────── rc= 0
───────── result= 22
═══════════════════════════════════════════════════════════════════════════════
</pre>
'''output''' using:
:::* PC/REXX
:::* Personal REXX
:::* R4 REXX
:::* ROO
<pre>
═══════════════════════════════════════════════════════════════════════════════
───────── SIGL= 5
───────── REXX source statement 5 = signal youWho /*line five. */
═══════════════════════════════════════════════════════════════════════════════
───────── rc= 0.333333333
───────── result= 22
═══════════════════════════════════════════════════════════════════════════════
───────── rc= 0.333333333
───────── result= 33
───────── hh= 33
═══════════════════════════════════════════════════════════════════════════════
Documents and Settings
Program Files
Recycled
System Volume Information
TEMP
WINDOWS
───────── rc= 0
───────── result= 33
═══════════════════════════════════════════════════════════════════════════════
</pre>
===version 2===
The REXX language has three special variables:
RC is set upon return from a command
RESULT is set or dropped after a CALL to a subroutine:
It is assigned the value given in the RETURN statement
or it is dropped when there was a RETURN without expression. (some REXX implementations set RESULT also upon return from a function invocation - see version 1 and the Discussion)
SIGL is set when control is tranferred within the REXX program.
(i.e. when a subroutine is called, a function is invoked, or a SIGNAL
instruction was used explicitly or as a result of a raised condition)
Note that RETURN transfers control but does not set SIGL.
<syntaxhighlight lang="rexx">'dir a2.txt'
Say 'rc='rc
'dir 33.*'
Say 'rc='rc
Call square 5
Say 'RESULT='result
Say 'SIGL='sigl
x2=square(3) /* just a simle example */
Say '3**2='||x2
Signal On Novalue
x=y /* y was not yet assigned a value */
Exit
square: Procedure Expose sigl
Say 'square was invoked from line' sigl':' sourceline(sigl)
Return arg(1)**2
Novalue:
Say 'NOVALUE encountered in line' sigl':' sourceline(sigl)
Exit </syntaxhighlight>
{{out}}
<pre> Datentr„ger in Laufwerk E: ist E_DESKTOP
Volumeseriennummer: 66C1-0469
Verzeichnis von E:\
28.07.2014 11:53 19.219 A2.txt
1 Datei(en), 19.219 Bytes
0 Verzeichnis(se), 198.658.433.024 Bytes frei
rc=0
Datentr„ger in Laufwerk E: ist E_DESKTOP
Volumeseriennummer: 66C1-0469
Verzeichnis von E:\
rc=1
square was invoked from line 6: Call square 5
RESULT=25
SIGL=6
square was invoked from line 10: x2=square(3) /* just a simle example */
3**2=9
NOVALUE encountered in line 14: x=y /* y was not yet assigned a value */ </pre>
=={{header|Ruby}}==
[http://ruby.wikia.com/wiki/Special_variable A list and description of Ruby's Special Variables]
=={{header|Scala}}==
Scala has only a few special variables. Inside an object there is this, a reference that points to the object itself (like 127.0.0.1 in networking) and are used to qualify member access. There is also super that does the same for the base class (actually "the next class in the inheritance tree").
Depending on the context, underscore has the following meaning:
<pre>import scala._ // Wild card -- all of scala is imported
import scala.{ Predef => _, _ } // Exception, everything except Predef
def f[M[_]] // Higher kinded type parameter
def f(m: M[_]) // Existential type
_ + _ // Anonymous function placeholder parameter
m _ // Eta expansion of method into method value
m(_) // Partial function application
_ => 5 // Discarded parameter
case _ => // Wild card pattern -- matches anything
val (a, _) = (1, 2) // same thing
for (_ <- 1 to 10) // same thing
f(xs: _*) // Sequence xs is passed as multiple parameters to f(ys: T*)
case Seq(xs @ _*) // Identifier xs is bound to the whole matched sequence
var i: Int = _ // Initialization to the default value
def abc_<>! // An underscore must separate alphanumerics from symbols on identifiers
t._2 // Part of a method name, such as tuple getters
var i: Int = _ // Initialization with a default value
for (_ <- 1 to 10) doIt() // Discarded val
def f: T; def f_=(t: T) // Combo for creating mutable f member.</pre>
=={{header|Smalltalk}}==
Talking about special (reserved) names, there are:
* self - the current method's receiver
* super - ditto, but different message send lookup
* thisContext - the current stackframe/aka active continuation
Everything else is found via the lexical scope ending in bindings in a namespace.
The global default namespace is called "Smalltalk" and contains (beside bindings for all classes by name) the singletons:
* true
* false
* nil
Technically, these could be redefined, but the system would not work if any of them was. Therefore most compilers refuse code which obviously attempts to do so, and we can think of them as being reserved names as well.
Global binding names are returned by <syntaxhighlight lang="smalltalk">Smalltalk keys</syntaxhighlight>
Things like the shell environment, command line argument, version numbers etc. are usually not exposed via globals, but instead held in private class variables (static variables), which can be accessed via getter messages (which, by the way, makes it easier to insert a dialect compatibility layer). An example for this would be: <syntaxhighlight lang="smalltalk">Float precision</syntaxhighlight> or <syntaxhighlight lang="smalltalk">Smalltalk version</syntaxhighlight>
Name conventions:
* class names - upperCase first
* class variables (statics) - ditto
* shared pool variables - ditto
* all other variables (incl. instance variables) - lowercase first
* method names - lowercase first; except for constant/parameter getters, which are sometimes uc-first
=={{header|Tcl}}==
Line 806 ⟶ 2,168:
:This local variable holds the Tcl list of arguments supplied to the current procedure after all the other formal arguments have been satisfied. Note that it needs to be explicitly listed in the formal arguments ''and'' be last in the list of formal arguments to have this behavior.
==
The following variables are reserved for special purposes within the Bourne shell:
* $0 the invoked command positional variable
* $1 the first positional variable
* $2 the second positional variable
* $3 the third positional variable
* $4 the fourth positional variable
* $5 the fifth positional variable
* $6 the sixth positional variable
* $7 the seventh positional variable
* $8 the eighth positional variable
* $9 the nineth positional variable
* $* the dollarstar expands to all command line arguments
* $@ the dollarsnail expands to all command line arguments
* $# the dollarhash expands to the number of command line arguments given
* $? the dollarhook expands to the exit status of the last command executed
* $- a list of all options used to invoke the shell
* $$ the pid of the currentprocess
* $! the pid of the last command executed as a background process
* CDPATH Additional locations to be searched by the cd command
* HOME The default working directory of the current user
* HUSHLOGIN
* IFS Internal field separator. This contains space,tab and newline characters
* LANG Determines the default locale in the absence of other locale related environment variables
* LC_ALL High precedence override for locale specific behaviour
* LC_CTYPE Determines locale specific character classification
* LOGNAME The login name of the user
* LS_COLORS
* MAIL The full pathname of the users mail file
* MAILCHECK The time limit that the shell timer uses before checking for new mail
* MAILPATH
* OPTARG
* OPTIND
* PATH The shell search path
* PPID
* PS1 Primary system prompt
* PS2 Secondary system prompt
* PS3 Ternary system prompt
* PS4 Forth system prompt
* PWD Current working directory
* SHACCT
* SHELL The name of the current shell
* SHLVL
* TERM The current terminal type
* TIMEOUT
* TZ The current timezone
* USER The current username
* underscore
=={{header|Ursa}}==
<syntaxhighlight lang="ursa"># contains arguments passed to the ursa
# interpreter on the command line
string<> args
# iodevice that points to the console by default
iodevice console
# contains "\n"
string endl
# represents false
boolean false
# represents true
boolean true</syntaxhighlight>
=={{header|VBA}}==
VBA does not have special variables.
=={{header|XLISP}}==
XLISP provides the following built-in variables:
<pre>*PACKAGE*
*READTABLE*
*ERROR-HANDLER*
*UNBOUND-HANDLER*
*LOAD-PATH*
*STANDARD-INPUT*
*STANDARD-OUTPUT*
*ERROR-OUTPUT*
*FIXNUM-FORMAT*
*HEXNUM-FORMAT*
*FLONUM-FORMAT*
*PRINT-CASE*
*SOFTWARE-TYPE*
T ; bound to #T
NIL ; bound to '()
OBJECT
CLASS</pre>
=={{header|Wren}}==
Wren has two special variables ''this'' and ''super''. When used in a constructor or instance method of a class. ''this'' refers to the current instance and ''super'' refers to a super-class whose constructor or (typically overridden) method you wish to invoke. Here's an example.
<syntaxhighlight lang="wren">class Parent {
construct new(name) {
_name = name
}
name { _name }
}
class Child is Parent {
construct new(name, parentName) {
_name = name
super(parentName) // call parent's constructor
}
name { _name } // overrides Parent's name method
printNames() {
System.print("My name is %(this.name) and my parent's name is %(super.name).")
}
}
var c = Child.new("John", "Fred")
c.printNames()</syntaxhighlight>
{{out}}
<pre>
My name is John and my parent's name is Fred.
</pre>
=={{header|Z80 Assembly}}==
It's somewhat debatable whether processor registers count as "variables," since they don't have a location in the address space but their contents can change. Excluding those for now, there are a few memory locations that have special meaning:
The following memory locations can be called as functions using the <code>RST</code> instructions. Each appears to take a byte as an operand, but in fact there are only 8 different "operands" and each is hardcoded in, which means that only one byte is needed to describe both the <code>RST</code> and the destination byte. Unfortunately, there is very little room for code in these areas, since each is only '''8 bytes long!''' Most of the time you'll put a jump to the actual routine you want to execute in these areas. The last one, <code>RST 38</code>, may allow more room for code depending on the system.
* &0000 - called with RST 00
* &0008 - called with RST 08
* &0010 - called with RST 10
* &0018 - called with RST 18
* &0020 - called with RST 20
* &0028 - called with RST 28
* &0030 - called with RST 30
* &0038 - called with RST 38
The memory location &0066 is special because it contains the NMI routine. NMI stands for "Non-Maskable Interrupt" and is a hardware interrupt that can't be stopped by a <code>DI</code> command. When an NMI occurs, the CPU will save the program counter on the stack and jump to &0066, and execute from there. The <code>RETN</code> instruction is used to return back to the main program. Usually an <code>ORG </code> directive is the easiest way to guarantee that your code will begin at the correct address for NMI. Since you can't predict exactly what state your program will be in when an NMI happens, it's important that the NMI routine uses either the stack or the exchange commands to preserve the register state at the start and restores it before returning. Otherwise, your NMI could ruin whatever your program was doing at the time.
Depending on the hardware, programming the NMI routine may not actually be your responsibility. It's usually only required when programming for a ROM-cartridge game console like the Sega Master System. On home computers, the NMI routine at &0066 is typically built into the firmware by the manufacturer and cannot be changed; however that routine will often contain a jump to another memory location that you can change indirectly using system calls and parameter passing.
<syntaxhighlight lang="z80">org &0066
NMI_HANDLER: ;this label is optional, the CPU doesn't need it to know how to jump here.
retn ;in this example, the NMI routine will immediately return without doing anything.</syntaxhighlight>
The <code>I</code> register handles the interrupt operation in <code>IM 2</code> mode. The Game Boy does not have this register, as it handles interrupts differently.
The <code>r</code> register handles memory refresh. You should '''not''' write to this register, as doing so can damage your hardware. But reading from this register is safe. It basically contains a pseudo-random value, and while its randomness isn't sufficient to reliably seed a PRNG, it can be used to add a little "salt" to a random value. (It should be noted that the Game Boy doesn't have this register, so don't bother trying.)
<syntaxhighlight lang="z80"> ld a,r ;read from the refresh register.</syntaxhighlight>
=={{header|zkl}}==
<syntaxhighlight lang="zkl">__DATE__, __DEBUG__, __FILE__, __LINE__, __NAME__, __TIME__</syntaxhighlight>
As in the C preprocessor. Some (like __DEBUG__) can be changed, others (like __LINE__, __TIME__) are constants.
=={{header|ZX Spectrum Basic}}==
The ZX Spectrum does Not make a difference between capital or lower character variable names. A normal variable can be severall letters long, any DEF FN, FOR/NEXT, DIM (STRING or DATA) array name is a single letter variable name. None of these are special variables. for 128k zx spectrum matters that In REVERSED SENSE some variable names are IMposible becouse of the tokenized form in the 48k basic eg 'not' will be NOT !!!!
There are a set of system variables held at a fixed memory addresses, which can be accessed via PEEK and POKE functions. The system variables and addresses are:
* 23552 KSTATE - Keyboard state.
Line 879 ⟶ 2,399:
* 23732 P-RAMT - Address of last byte of physical RAM.
<
20 PRINT "The ramtop address is "; PEEK (23730) + 256 * PEEK (23731): REM ramtop
30 POKE 23609,50: REM set keyboard pip to 50</
{{omit from|GUISS|Does not have any variables at all}}
{{omit from|68000 Assembly|Existence of special variables depends entirely on the implementation}}
{{omit from|8086 Assembly|Existence of special variables depends entirely on the implementation}}
{{omit from|x86 Assembly|Existence of special variables depends entirely on the implementation}}
{{omit from|ARM Assembly|Existence of special variables depends entirely on the implementation}}
|