Variables: Difference between revisions
Content deleted Content added
(18 intermediate revisions by 9 users not shown) | |||
Line 15:
=={{header|11l}}==
To declare <code>a</code> as an integer:
<syntaxhighlight lang
Type of variables may be inferred:
<
Multiple variables may be defined in a single line as follows:
<syntaxhighlight lang
=={{header|360 Assembly}}==
;assignment, reference, referencing:
<
L 2,F assigment r2=f
* reference (or address) of F
LA 3,F reference r3=@f
* referencing (or indexing) of reg3 (r3->f)
L 4,0(3) referencing r4=%r3=%@f=f</
;declarations, initialization, datatypes:
<
C DS C character 1
X DS X character hexa 1
Line 54:
SI DC CL12'789' string 12
PI DC PL16'7' packed decimal 16
ZI DC ZL32'7' zoned decimal 32</
;scope
In BAL (Basic Assembler Language), variables are global and there is no scope.
=={{header|6502 Assembly}}==
===Declaration===
Declaration is not actually needed in 6502 Assembly. Any portion of RAM can be read or written at any time. However, it is very helpful to use descriptive labels of memory locations. Different assemblers handle this differently, with directives such as "Equals" <code>equ</code>, "Enumerate" <code>.enum</code>, "Reserve Storage Space" <code>.rs</code>, or "Define Storage Bytes:<code>.dsb</code>. These directives allow you to name a memory address to something you can more easily remember than an arbitrary number. One important caveat to note is that the <code>equ</code> directives do not take up space in your program. This is easier to illustrate with an example than explain in words:
<
SoundRam equ $1200 ;some assemblers require equ directives to not be indented.
SoundChannel_One equ $1200
SoundChannel_Two equ $1201
SoundChannel_Three equ $1202
LDA #$FF ;this still gets assembled starting at $1200, since equ directives don't take up space!</
Line 73 ⟶ 72:
The <code>equ</code> method:
<
Player_Xpos equ $01 ;this variable is located at $01
Player_Ypos equ $02
pointer equ $03 ;intended to take up 2 bytes
sound_on equ $05</
The <code>enum</code> method:
<
;these will be defined starting at $0000 and increasing in the order listed, incremented by the amount after DSB.
joystick dsb 1 ;this takes up 1 byte
Line 87 ⟶ 86:
pointer dsb 2 ;this takes up 2 bytes
sound_on dsb 1
ende ;end enumeration</
The <code>rs</code> method:
<
joystick .rs 1
Player_Xpos .rs 1
Line 96 ⟶ 95:
pointer .rs 2
sound_on .rs 1
;no closer needed for this method</
===Initialization===
Line 103 ⟶ 102:
===Assignment===
Assignment is done by storing values into memory. Variables larger than 8 bits will need to be loaded in pieces.
<
STA Player1_Lives ;equivalent C code: Player1_Lives = 5;
Line 110 ⟶ 109:
LDA #$40
STA pointer
;loads the variable pointer with the value $0540</
===Datatypes===
Line 121 ⟶ 120:
Labels are always defined at compile time. The assembler converts each label into the value or address it represents as part of the assembling process. The CPU doesn't know the labels even exist; labels are simply a convenience for the programmer. Once defined, a label can be used in place of an address or value.
<
VRAM_ADDR equ $2006 ;label referring to a memory address
VRAM_DATA equ $2007 ;label referring to a memory address
Line 131 ⟶ 130:
LDA #$03
STA VRAM_DATA</
=={{header|68000 Assembly}}==
Typically a variable is just a named memory location that exists in RAM. For ROM cartridge software, <code>equ</code> directives are used to assign names to memory locations. For programs that run from disk, which are loaded into RAM and executed from there, the <code>DC</code> directives can also be used, and then the programmer places a label in front of those directives.
<
DC.L 0 ;reserves 4 bytes of storage. The label MyVar represents the address of the four 0 bytes shown here.
MyOtherVar:
DC.L $C0 ;reserves 8 bytes of storage. The first four bytes are initialized to 00 00 00 C0 and the second four to $00 $00 $01 $F4.
DC.L 500 ;MyOtherVar points to the first four bytes, you'll need pointer arithmetic to get to the second four.</
=={{header|8086 Assembly}}==
A variable is just a value in some memory location that can be read from and written to. Declaring a variable in an assembler can be done with labels. If your code is executed from RAM, as is the case with most home computers, variables can be initialized prior to runtime.
<
MyVar word 0FFFFh ;the leading zero is just to help the assembler tell that this is a number, it's not actually part of the variable.
.code
mov ax, word ptr [ds:MyVar]</
Programs written for ROM cartridge-based systems like the WonderSwan can't use the method above to initialize variables at compile time; however the programmer can equate a memory location with a label that describes what will be stored there. Unfortunately this means that you can't be sure what the system's RAM will contain at startup, so you'll usually have to wipe it clean before the user is allowed to play.
<
mov al,3
mov byte ptr [Player1_Lives],al ;give the player 3 lives to start the game with</
Scope is a little more complicated on 8086 Assembly than most other assembly languages. The segmented memory model means that a segment register must point to the segment where a variable is located before it can be used; however in practice this takes little effort on the programmer's part, regardless of where they are in the program. There is nothing stopping you from changing the values stored in segment registers, however if you have multiple variables in multiple different segments you'll end up juggling which segments are accessible at a given point, which is not a good place to be. Fortunately, you don't need to actually remember which segment a labeled variable is stored in, as the assembler can work that out for you:
<
mov ds,ax ;load this segment into the data segment register.</
Some segments, such as those for video memory, can't be reliably looked up with <code>seg</code>. Thankfully, they're nearly always constant values, so you can just use an <code>equ</code> directive to label them.
Line 168 ⟶ 167:
=={{header|8th}}==
There is only one type of variable in 8th, and it is simply a single-item container which can contain any of the known data-types:
<
\ declare a variable which is initialized to the number '0'
var x
Line 180 ⟶ 179:
\ Change the cat to a dog:
"dog" y !
</syntaxhighlight>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program variable64.s */
Line 245 ⟶ 244:
qAdriInteger2: .quad iInteger2 // variable address iInteger2
</syntaxhighlight>
=={{header|Ada}}==
<
A : constant Integer := 42; -- Create a constant
X : String := "Hello"; -- Create and initialize a local variable
Line 266 ⟶ 265:
...
end;
end Name; -- End of the scope</
=={{header|ALGOL 68}}==
Local variables are generally called '''local''' variables in ALGOL 68. Variables must be declared before use. In traditional ALGOL 68, variables must be declared before any '''labels:''' in a '''compound-clause'''. The declaration of a variable, without assigning a value takes the form: <b><typename></b> <i><variablename>;</i>
<syntaxhighlight lang
Some common types are: '''char''', '''string''', '''short int''', '''int''', '''long int''', '''real''', '''long real''', '''bits''' and '''bytes''' .
Multiple variables may be defined in a single statement as follows:
<
It is possible to initialize variables with expressions having known values when they are defined.
The syntax follows the form <i><typename> <variablename> := <initializing expression>;</i>
<
LONG INT elwood = 3*bsize, jake = bsize -2;</
The '''string'''s in ALGOL 68 are '''flex''' arrays of '''char'''. To declare initial space for a string of exactly to 20 characters, the following declaration is used.
<syntaxhighlight lang
All arrays are structure that include both the lower '''lwb''' and upper '''upb''' of the array. Hence '''string'''s in ALGOL 68 may safely contain ''null character''s and can be reassigned with longer or shorter strings.
To declare an initialized string that won't be changed the following declaration may be used:
<
There are more rules regarding arrays, variables containing pointers, dynamic allocation,
and initialization that are too extensive to cover here.
Line 301 ⟶ 300:
before the first executable statement.
Declaration is separate from initialisation - there is no separate initialisation syntax (except for fields of a record - see below), normal assignments are used:
<
integer a1, a2; real b; long real c; complex d; long complex f;
logical g; bits h; string(32) j;
Line 308 ⟶ 307:
f := d := c := b := a2 := a1 := 0; % multiple assignment %
g := false; h := #a0; j := "Hello, World!";
</syntaxhighlight>
Records can be declared, composed of fields of the basic types and references to records. E.g.:
<
reference(R1) ref1, ref2;</
In the above, R1 is a structure containing an integer and a string. Ref1 and ref2 are variables that will refer to instances of the R1 structure.
References can be declared that can refer to a number of different record structures. The allowable references must be specified in the declaration E.g.:
<
record date( integer day, month, year );
reference(person, date) ref3;</
In the above, ref3 can hold references to either a person or a date.
Variables that are references to the basic types are not allowed. E.g.:
<
The following could be used instead:
<
reference(INT_VALUE) refInt;</
Fields are referred to via a function-like notation, e.g.:
<
reference (person) someone;
someone := person % create a new person structure with uninitialised fields %
Line 332 ⟶ 331:
age(someone) := 27;
% could also initialise the fields when the record is created: %
someone := person( "Harry", 32 );</
Arrays of the basic types and references can also be declared, but records cannot contain arrays.
Line 339 ⟶ 338:
=={{header|Apex}}==
<syntaxhighlight lang="apex">
// If not initialized at class/member level, it will be set to null
Integer x = 0;
Line 355 ⟶ 354:
Boolean b = true;
AClassName cls = new AClassName();
</syntaxhighlight>
=={{header|AppleScript}}==
Variables are untyped in AppleScript, but they must be instantiated before use.
Example:<syntaxhighlight lang
Scope may be explicitly defined before instantiation using either the <code>global</code> or <code>local</code> declarations.<
set x to 1
local y
set y to 2</
Where a variable has both local and global instances, it is possible to use the <code>my</code> modifier to access the global (top-level) instantiation.
Example:<
set x to 0 -- implicit local
return x
Line 379 ⟶ 378:
return {localx(), globalx()}
end run
--> RETURNS: {0, 1}</
Applescript also supports top-level entities known as <code>properties</code> that are global to that script.
Example:<syntaxhighlight lang
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program variable.s */
Line 447 ⟶ 446:
iAdriInteger2: .int iInteger2 @ variable address iInteger2
</syntaxhighlight>
=={{header|Arturo}}==
<
str: "hello world"
Line 466 ⟶ 465:
]
inspect symbols</
=={{header|AutoHotkey}}==
<
z := 3 + 4 ; assign an expression
if !y ; uninitialized variables are assumed to be 0 or "" (blank string)
Line 478 ⟶ 477:
global y ;
static z=4 ; initialized once, then value is remembered between function calls
}</
=={{header|AWK}}==
===Dynamic variables===
<
# Variables are dynamically typecast, and do not need declaration prior to use:
fruit = "banana" # create a variable, and fill it with a string
Line 501 ⟶ 500:
print "a,b,c=",a,b,c, "c+0=", c+0, 0+c
print "a+b=", a+b, "b+c=", b+c
}</
{{Out}}
<pre>
Line 515 ⟶ 514:
===Assignment on commandline===
It is possible to assign value to variables from the commandline:
<
BEGIN {
y = 3
Line 521 ⟶ 520:
print "x,y,z:", x,y,z
printf( "x=%d,y=%d,z=%d:", x,y,z )
}</
{{Out}} with "-v x=9":
<pre>
Line 540 ⟶ 539:
by listing the variable as an additional dummy function argument
after the required arguments:
<
# s is an argument passed from caller
# k is a dummy not passed by caller, but because it is
Line 554 ⟶ 553:
foo(s,k)
print "k still is", k
}</
{{Out}}
<pre>
Line 572 ⟶ 571:
* NF is the number of fields
*$NF is the contents of the last field.
<
echo -e "2 apples 0.44$ \n 3 banana 0.33$" | awk '{p=$1*$NF; sum+=p; print $2,":",p; }; END{print "Sum=",sum}'</
With more data, this would look like
awk '{p=$1*$NF; sum+=p; print $2,":",p; }; END{print "Sum=",sum}' inputfile
Line 588 ⟶ 587:
In Axe, variables are global because they are (mostly) static references to memory locations. This means there is also no scope.
<syntaxhighlight lang
The letters A-Z and theta are all general-purpose variables. They are located at the end of the L₁ memory region by default, but they can be reallocated to any region of free memory:
<syntaxhighlight lang
The variables r₁ through r₆ are used for function arguments. They are automatically set as the arguments passed to the function. However, they behave otherwise just like normal variables.
Line 601 ⟶ 600:
In BASIC, variables are global and there is no scope. However, it is an error to reference a variable before it has been assigned.
<
20 LET B%=1.3: REM The sigil indicates an integer, so this will be rounded down
30 LET C$="0121": REM The sigil indicates a string data type. the leading zero is not truncated
Line 616 ⟶ 615:
140 LET D(11)=6: REM This is an error because d only has 10 elements
150 PRINT F%: REM This is an error because we have not provided an element number
160 END</
==={{header|Applesoft BASIC}}===
Line 623 ⟶ 622:
The LET keyword is optional. Almost all math is done using floating point numbers by default. Using floating point variables is almost always faster than using integer variables which require extra conversion between floating point and integer. Integers use less space than floating point values. Applesoft BASIC array indexes start at zero.
<
20 LET B% = 1.7: REM THE PERCENT SIGN INDICATES AN INTEGER; THIS GETS TRUNCATED DOWN
30 LET C$ = "0121": REM THE DOLLAR SIGN INDICATES A STRING DATA TYPE. THE LEADING ZERO IS NOT TRUNCATED
Line 637 ⟶ 636:
130 PRINT D(0): REM THIS IS NOT AN ERROR BECAUSE ELEMENTS ARE NUMBERED FROM ZERO.
140 PRINT F%: REM THIS PRINTS 0 BECAUSE F% IS A DIFFERENT VARIABLE THAN THE ARRAY F%(10)
150 LET D(21) = 6: REM THIS IS AN ERROR BECAUSE D ONLY HAS 21 ELEMENTS INDEXED FROM 0 TO 20.</
==={{header|Commodore BASIC}}===
Line 674 ⟶ 673:
'''Demonstration Program'''
<
5 rem commodore basic variable demonstration
10 print chr$(147);chr$(14);:ti$="000000":rem see lines 420-460
Line 795 ⟶ 794:
5510 print chr$(19);"Time: "left$(ti$,2)":"mid$(ti$,3,2)":"right$(ti$,2);
5515 get k$:if k$="" then 5510
5520 print chr$(147);:return</
'''Modifications for Enhanced TIME$'''
Line 801 ⟶ 800:
Some models allow <code>TI$</code> to be a '''seven digit''' number able to track 1/10 seconds as the final digit. Use the following modifications for those models (e.g. CBM-II):
<
430 t$=left$(ti$,2)+":"+mid$(ti$,3,2)+":"+mid$(ti$,5,2)+"."+right$(ti$,1)
Line 812 ⟶ 811:
5515 print chr$(19);"Time: "t$
5520 get k$:if k$="" then 5510
5525 print chr$(147);:return</
==={{Header|Tiny BASIC}}===
<
REM They start off initialised to zero.
PRINT A
Line 844 ⟶ 843:
REM Tiny Basic does not support arrays or pointers. Strings can
REM be used, but only as string constants within a PRINT statement.</
=={{header|Batch File}}==
Batch file variables are not limited to data types and they do not need to be initialized before use.
<
@echo off
Line 866 ⟶ 865:
set myString
pause>nul
</syntaxhighlight>
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
REM the type is explicitly indicated by means of a suffix character.
REM Variable names must start with A-Z, a-z, _ or `, and may contain
Line 902 ⟶ 901:
REM All variables in BBC BASIC have global scope unless they are used
REM as a formal parameter of a function or procedure, or are declared
REM as LOCAL or PRIVATE. This is different from most other BASICs.</
=={{header|Boo}}==
Line 962 ⟶ 961:
BQN variables are declared and initialized using the <code>←</code> symbol. The following code block creates a variable <Code>a</code> with value 10.
<syntaxhighlight lang
Variables can be modified using the <code>↩</code> symbol after they are declared.
Line 977 ⟶ 976:
<strong>Variable declaration.</strong>
Variables local to a function (<code>i</code> and <code>j</code> in the example below) can be declared just before the body of a function.
<
Global variables are created the first time they are assigned a value.
Line 1,002 ⟶ 1,001:
=={{header|C}}==
Local variables are generally called <i>auto</i> variables in C. Variables must be declared before use. The declaration of a variable, without assigning a value takes the form <i><typename> <variablename>;</i>
<syntaxhighlight lang
Some common types are: <i>char, short, int, long, float, double</i> and <i>unsigned</i>.
Multiple variables may be defined in a single statement as follows:
<syntaxhighlight lang
It is possible to initialize variables with expressions having known values when they are defined.
The syntax follows the form <i><typename> <variablename> = <initializing expression>;</i>
<
long elwood = 3*BSIZE, jake = BSIZE -2;</
Strings in C are arrays of char terminated by a 0 or NULL character. To declare space for a string of up to 20 characters, the following declaration is used.
<syntaxhighlight lang
The extra length leaves room for the terminating 0.
To declare an initialized string that won't be changed the following declaration may be used:
<
There are more rules regarding arrays, variables containing pointers, dynamic allocation,
and initialization that are too extensive to cover here.
Line 1,025 ⟶ 1,024:
They are declared with the type first, as in C:
<syntaxhighlight lang
Multiple variables may be defined in a single line as follows:
<syntaxhighlight lang
It is also possible to assign variables, either while declaring or in the program logic:
<
int b;
int c = Func(a);
b = 5;</
=={{header|C++}}==
Much like C, C++ variables are declared at the very start of the program after the headers are declared.
To declare a as an integer you say: the type of variable; then the variable followed by a semicolon ";".
<syntaxhighlight lang
From C++11, type of variables may be inferred:
<
Template variables are specified with template parameters in angle brackets after the class name:
<syntaxhighlight lang
=={{header|Caché ObjectScript}}==
Variable type is not declared for local variables.
<syntaxhighlight lang="text">set MyStr = "A string"
set MyInt = 4
set MyFloat = 1.3</
Array variables use a subscript as an element index.<br />
Line 1,058 ⟶ 1,057:
Arrays are automatically sorted by subscript.<br />
<syntaxhighlight lang="text">set MyArray(1) = "element 1"
set MyArray(2) = "element 2"
set MyArray(2,1) = "sub element 1 of element 2"
set MyArray("Element 3") "element indexed by a string"
set MyArray = "Root element"
</syntaxhighlight>
Global variables are persistent. They remain set even after reboot.<br />
Global variables work the same as array variables.<br />
Global variables are indicated with the '^' character.<br />
<syntaxhighlight lang="text">
set ^MyGlobal("a subscript") = "My Value"
</syntaxhighlight>
Process private global variables exist for the lifetime of the process, can only be accessed by the process that instantiated it and are indicated as follows:
<syntaxhighlight lang="text">
set ^||MyProcessPrivateGlobal("subscript 1") = "value"
</syntaxhighlight>
=={{header|ChucK}}==
Much like C or C++, declared but not initialized:
<syntaxhighlight lang="text"> int a; </
Multiple declaration:
<syntaxhighlight lang="text">int b,c,d; </
Declared and initialized:
<syntaxhighlight lang="text">0 => int e;</
=={{header|Clojure}}==
Line 1,088 ⟶ 1,087:
'''Declaration only:'''
<syntaxhighlight lang
<syntaxhighlight lang
'''Global scope initialization:'''
<syntaxhighlight lang
<syntaxhighlight lang
<
<
'''Local scope initialization:'''
<
'''Local re-binding of dynamic global var:'''
<
(binding [foo 20] ...)</
Clojure is a dynamically typed language, but does support the use of type-hints in the form of metadata. This can improve performance when interop with the host language would otherwise cause reflection:
<
(.length x))</
For mutable programming, Clojure provides '''atom'''s, '''ref'''s, and '''agent'''s. These can be stored in a var to allow managed, thread-safe mutation. '''atom'''s are the most common way to store state, but '''ref'''s and '''agent'''s can be used when ''coordinated'' and ''asynchronous'' functionality is required, respectively.
<
<
<
=={{header|COBOL}}==
Line 1,118 ⟶ 1,117:
===Assignment===
Variables can be assigned values using either <code>MOVE</code> or <code>SET</code>. <code>SET</code> is used for assigning values to indexes, pointers and object references, and <code>MOVE</code> is used for everything else.
<
MOVE FUNCTION SOME-FUNC(x) TO y
MOVE "foo" TO z
MOVE "values 1234" TO group-item
SET some-index TO 5</
One of COBOL's more well-known features is <code>MOVE CORRESPONDING</code>, where variables subordinate to a group item are assigned the values of variables with the same names in a different group item. The snippet below uses this to reverse the date:
<
03 year PIC 9(4).
03 FILLER PIC X VALUE "-".
Line 1,142 ⟶ 1,141:
MOVE "2012-11-10" TO normal-date
MOVE CORR normal-date TO reversed-date
DISPLAY reversed-date *> Shows '10-11-2012'</
===Declaration===
Line 1,156 ⟶ 1,155:
Variable type is defined in a <code>PICTURE</code> clause and/or a <code>USAGE</code> clause. <code>PICTURE</code> clauses can be used like so:
<
01 b PIC 9(10). *> b is a 10-digit integer.
01 c PIC 9(10)V9(5). *> c is a decimal number with a 10-digit integral part and a 5-digit fractional part.
01 d PIC 99/99/99. *> d is an edited number, with a slash between each pair of digits in a 6-digit integer.</
The <code>USAGE</code> clause is used to define pointers, floating-point numbers, binary numbers, [http://en.wikipedia.org/wiki/Binary-coded_decimal#Packed_BCD packed decimals] and object references amongst others.
Line 1,166 ⟶ 1,165:
Variables with higher level-numbers are subordinate to variables with lower level-numbers.
The 77 level-number indicates the variable has no subordinate data and is therefore not a group item. Group items can include <code>FILLER</code> items which are parts of a group item which are not directly accessible.
<
01 group-item.
03 sub-data PIC X(10).
03 more-sub-data PIC X(10).</
===Initialization===
Initialization is done via the <code>VALUE</code> clause in the <code>DATA DIVISION</code> or via the <code>INITIALIZE</code> statement in the <code>PROCEDURE DIVISION</code>. The <code>INITIALIZE</code> statement will set a variable back to either the value in its <code>VALUE</code> clause (if <code>INITIALIZE</code> has a <code>VALUE</code> clause) or to the appropriate value out of <code>NULL</code>, <code>SPACES</code> or <code>ZERO</code>.
<
WORKING-STORAGE SECTION.
01 initialized-data PIC X(15) VALUE "Hello, World!".
Line 1,180 ⟶ 1,179:
PROCEDURE DIVISION.
DISPLAY initialized-data *> Shows 'Hello, World!'
DISPLAY other-data *> Will probably show 15 spaces.</
Group items can be initialized, but they are initialized with a string like so:
<
03 a-string PIC X(6). *> Contains "Hello!"
03 a-number PIC 9(5). *> Contains '12345'.</
===Reference Modification===
Reference modification allows a range of characters to be taken from a variable.
<
some-num (1:3) *> Get the first three digits from the number
another-string (5:) *> Get everything from the 5th character/digit onwards.
*> To reference modify an array element
some-table (1) (5:1) *> Get the 5th character from the 1st element in the table</
===Scope===
Line 1,206 ⟶ 1,205:
Special variables may be defined with '''defparameter'''.
<
Here, the variable '''*x*''' is assigned the value nil. Special variables are wrapped with asterisks (called 'earmuffs'). The third argument is a docstring.
Line 1,212 ⟶ 1,211:
We may also use '''defvar''', which works like '''defparameter''' except that '''defvar''' won't overwrite the value of the variable that has already been bound.
<
It does, however, overwrite the docstring, which you can verify:
<
'''defconstant''' works in the same way, but binds a constant. Constants are wrapped with '+' signs rather than earmuffs.
Line 1,224 ⟶ 1,223:
For local varibles, we use let:
<
hobo-joe)
(apply #'+ jenny))</
The symbols 'jenny' and 'hobo-joe' are ''lexically bound'' meaning that they are valid within the scope of the let block. If we move the apply form out of scope, the compiler will complain that 'jenny' is unbound.
Line 1,234 ⟶ 1,233:
Common Lisp prefers to use variables in lexical, rather than dynamic scope. If we've defined *x* as a special variable, then binding it lexically with '''let''' will create a new local value while leaving the dynamically scoped *x* untouched.
<
(let ((*x* 43))
(print *x*)
(print *x*))</
If *x* has previously been bound to the value 42, then this example will output 43, then 42.
Line 1,245 ⟶ 1,244:
We use '''setf''' to modify the value of a symbol.
<syntaxhighlight lang
We can also modify multiple symbols sequentially:
<
=>43</
The return value is of the last form evaluated. In that example, '''*x*''' is referred to twice, and the value applied to '''*y*''' depends on the modified value of '''*x*'''. We can use '''psetf''' to set variables in parallel:
<
(psetf *x* 42 *y* (1+ *x*)
=>NIL</
The return value is NIL, but the resulting value of '''*y*''' is 626 instead of 43.
Line 1,263 ⟶ 1,262:
Common Lisp is dynamically typed, so we don't have to explicitly tell it what type of value a symbol holds. We nonetheless have the option of being explicit about which types our functions use through '''ftype''' declarations, which tell the compiler what to expect:
<
(defun frobnicate (x)
(+ x 42))</
In this example, the function '''frobnicate''' must be written to take one fixnum (i.e., a fixed-width integer as opposed to a bignum) and must return a fixnum. Having been given this type information, the compiler can now assert that the function works the way we've told it it does, and will throw an error when you've made a mistake in implementing or calling the function. The compiler may also use more performant fixnum-specific arithmetic functions instead of the generic arithmetic functions.
Line 1,271 ⟶ 1,270:
You can give the compiler the same information using in-function type declarations and the '''the''' operator:
<
(declare (type fixnum x))
(the fixnum (+ x 128)))</
The '''declare''' statement applies to the function in which the statement appears. In the example, we assert to the compiler that '''x''' is a fixnum. In some compilers, '''the''' tells the compiler the type returned by an expression; we want our '''frobnicate''' to only ever return a fixnum and to throw an error if anything causes the return value to be anything other than a fixnum.
=={{header|D}}==
<syntaxhighlight lang="d">
float bite = 36.321; ///_Defines a floating-point number (float), "bite", with a value of 36.321
float[3] bites; ///_Defines a static array of 3 floats
float[] more_bites; ///_Defines a dynamic array of floats
</syntaxhighlight>
=={{header|DBL}}==
<syntaxhighlight lang="dbl">;
; Variables examples for DBL version 4 by Dario B.
;
Line 1,357 ⟶ 1,356:
ALPA1[2,1](3,4)="FO"
;.....................
</syntaxhighlight>
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">var
i: Integer;
s: string;
Line 1,373 ⟶ 1,372:
o.Free;
end;
end;</
=={{header|DM}}==
Line 1,379 ⟶ 1,378:
Declaring variables:
<
// var -> <varname>
var/x
Line 1,391 ⟶ 1,390:
// And like this, still a tree structure.
var/x, y
</syntaxhighlight>
The type of a variable can be declared like this, note that there is are types for strings or numbers:
<
var/obj/x
// It can also be defined like this, because of the tree structure:
Line 1,407 ⟶ 1,406:
// ...
// You get the idea
</syntaxhighlight>
Variables can be assigned, during declaration or later. The compiler does not enforce types here at all.
<syntaxhighlight lang="dm">
var/x = 0
x = 10
var/y
y = "hi!"
</syntaxhighlight>
=={{header|Diego}}==
Line 1,444 ⟶ 1,443:
<b>examples:</b>
<
dim(v1);
add_var(v1, v2, v3, v4);
Line 1,453 ⟶ 1,452:
dim(greeting)_dt(string);
add_var({date}, birthdate);
dim({date}, birthdate);</
Variables can also be declared at posit state. So, verb-object <code>add_var</code> becomes posits <code>_addvar</code> or, shortened, <code>_var</code>; action <code>dim</code> becomes a posit. So, for example, during a robot manoeuvre a variable can be declared:
<
go_robot(beh)_waypoint(waypoint1)_var({bool},behArriveWaypoint1);
go_robot(teh)_waypoint(waypoint1)_dim({bool},tehArriveWaypoint1);</
===Initialisation===
Line 1,475 ⟶ 1,474:
Initialisation at declaration:
<
dim({double},realNumber)_v(3.0);
add_var({boolean},isRaining)_v(false);
add_var(greeting)_datatype(string)_value(Hello, this is World speaking.);</
Initialisation after declaration:
<
[myinteger]_value(33);</
Dynamic initialisation after declaration:
<
[datename]_v(24-Jun-[myYearVar]);</
Variables that are not initialised are determined to be <code>undefined</code>. The callee can be sensitive to uninitialised (undefined) variables with its undefined sensitivity setting <code>set_undefined()_sensiti();</code>. So, for instance, if a callee is sensitive to a undefined variable, it will ask the caller and others in the mist for the declaration of the variable with command <code>with_var(<i>variablename</i>)_askdec();</code>.
Line 1,501 ⟶ 1,500:
<b>examples:</b>
<
with_var(E)_calc([m]*[c]^2);
with_var(d)_calc([b]^2-4*[a]*[c]);</
<!--(fullname)_calc([firstname]&" "&[lastname]);
(c)_calc(++);
([c])_calc(+=[a]);
([c]+[b]);</
Note, instead of using the <code>_calc</code> posit, all operators can be also be posits, for example:
<
with_var(c)_inc(); // increment by one
with_var(c)_inc(a); // same as with_var(c)_exp(+=[a]);</
<!-- <
(c)_inc(); // increment by one
(c)_inc(a); // same as [c]_exp(+=[a]);</
===Datatypes===
Line 1,542 ⟶ 1,541:
<b>examples:</b>
<
dim({double},myNumber)_v(3.0);
with_var(wholenumber)_datatype(integer);
with_var({boolean},isRaining)_value(false); // cast/converting datatype</
<!-- ({boolean},isRaining)_value(false); // cast/converting datatype</
However, datatypes can be implied to be variables using verb-object and posit commands, as such:
Line 1,562 ⟶ 1,561:
<b>examples:</b>
<
alert_human(bob)_msg(Hi [bobName]); // Hi Bob
alert_human(fred)_msg(Hi [fredName])_str(fredName)_value(Freddy); // Hi Freddy</
===Scope===
Line 1,572 ⟶ 1,571:
<b>For example:</b>
<
or
<
This command will share the variable <code>greeting</code> and its value with all thingys, but, the other thingys that received this command will not act upon it because they know this variable is for the exclusive use of the caller (<code>me</code>). This is <b>discernment</b>.
Line 1,582 ⟶ 1,581:
However, the command...
<
...will share and use the variable <code>greeting</code> and its value with all thingys that received this command. This is <b>swarmation</b>.
Line 1,588 ⟶ 1,587:
However, the command...
<
...will share the variable <code>greeting</code> and its value with all thingys that received this command, but only the computer named <code>cmp1</code> will use/act upon this variable. This is <b>discrimination</b>.
<!--
<
...this command will display, via a media on <code>alif</code>'s choosing, the message "Hello World". However,...
<syntaxhighlight lang
...this command will display the message "Hello World" on every robot that receives the command. However,...
<syntaxhighlight lang
...this command will display the message "Hello World" on every computer that receives the command (but not any robots). However,...
<
...this command will display the message "Hello World" on every computer that is running Microsoft® Windows&tm; that receives the command (but not any robots), and so on... -->
Line 1,619 ⟶ 1,618:
<b>For example:</b>
<
add_var({int},b); // b = undefined integer
Line 1,655 ⟶ 1,654:
with_var(varname)_v(b); // varname = "b"
with_var[varname]_v(0); // b = 0
([varname])_v(1); // b = 1 // same as `with_var(b)_v(1);`</
The default reference to a variable using <code>[]</code>, refers to the adjacent variable reading from left to right, regardless of whether the variable is named or unnamed, for example:
<
alert_human(gab)_msg(Hi [])_str()_v(Gabriella); // Hi Gabriella
Line 1,665 ⟶ 1,664:
alert_human(annamarie)_msg(Hi [])_str([a]+'-'[m])_str(a)_v(Anna)_str(m)_v(Marie); // Hi Anna-Marie
alert_human(annamarie)_msg(Hi []+'-'+[])_str()_v(Anna)_str()_v(Marie); // Hi Anna-Marie
alert_human(annamarie)_msg(Hi [])_str([]+'-'[])_str()_v(Anna)_str()_v(Marie); // Hi Anna-Marie</
Inside various posits, such as, <code>_calc</code> or <code>_msg</code>, the square brackets <code>[]</code> are used to escape into variables. Single quote marks can also be used to escape literals, but are optional.
Line 1,671 ⟶ 1,670:
<b>For example:</b>
<
alert_human(jill)_msg('Hi '+[jillName]+' Daniels')_var(jillName)_value(Jill); // Hi Jill Daniels
add_var(jillFullName)_calc([jillName]+" Daniels");</
=={{header|DWScript}}==
Line 1,679 ⟶ 1,678:
See [[Variables#Delphi|Delphi]] for "classic" declaration. In DWScript, if variables have to be declared ''before'' use, but can be declared inline, and their type can also be inferred.
<syntaxhighlight lang="delphi">
var i := 123; // inferred type of i is Integer
var s := 'abc'; // inferred type of s is String
var o := TObject.Create; // inferred type of o is TObject
var s2 := o.ClassName; // inferred type of s2 is String as that's the type returned by ClassName
</syntaxhighlight>
=={{header|Dyalect}}==
<
let pi = 3.14
Line 1,733 ⟶ 1,732:
base.x
}
}</
=={{header|E}}==
Line 1,741 ⟶ 1,740:
An identifier occurring in a pattern is a simple non-assignable variable. The <code>def</code> operator is usually used to define local variables:
<
x + x # returns 2</
<!-- Using bold rather than == so as to keep the TOC sane -->
Line 1,749 ⟶ 1,748:
The pattern <code>var <var>x</var></code> makes <var>x</var> an assignable variable, and <code>:=</code> is the assignment operator.
<
x := 2
x # returns 2</
(As a shorthand, <code>var x := ...</code> is equivalent to <code>def var x := ...</code>.)
Line 1,757 ⟶ 1,756:
There are update versions of the assignment operator, in the traditional C style (<code>+=</code>, <code>-=</code>, <code>|=</code>, etc.), but also permitting any verb (method name) to be used:
<
x += 1 # equivalent to x := x + 1, or x := x.add(1)
x # returns 2
Line 1,763 ⟶ 1,762:
def var list := ["x"]
list with= "y" # equivalent to list := list.with("y")
list # returns ["x", "y"]</
'''Patterns'''
Line 1,769 ⟶ 1,768:
Since variable definition is part of pattern matching, a list's elements may be distributed into a set of variables:
<
However, ''assignment'' to a list as in Perl or Python is not currently supported.
<
'''Scoping'''
Line 1,779 ⟶ 1,778:
In E, a variable is visible from the point of its definition until the end of the enclosing block. Variables can even be defined inside expressions (actually, E has no statement/expression distinction):
<
list[0] == x # x is still visible here; returns true</
'''Slots'''
Line 1,786 ⟶ 1,785:
The difference between assignable and non-assignable variables is defined in terms of primitive operations on non-primitive ''[http://wiki.erights.org/wiki/Slot slot]'' objects. Slots can also be employed by programmers for effects such as variables which have an effect when assigned (e.g. <code>backgroundColor := red</code>) or automatically change their values over time, but that is beyond the scope of this task. For example, it is possible to transfer a variable between scopes by referring to its slot:
<
var a := 0
var b := 0
Line 1,795 ⟶ 1,794:
x := 3
y := 4
sum() # returns 7</
As suggested by the <code>&</code> syntax, the use of slots is somewhat analogous in effect to C pointers or C++ references, allowing the passing of ''locations'' and not their values, and "pass-by-reference" or "out" parameters:
<
counter += 1
return counter
Line 1,806 ⟶ 1,805:
var idc := 0
getUniqueId(&idc) # returns 1
getUniqueId(&idc) # returns 2</
=={{header|EasyLang}}==
<syntaxhighlight lang=text>
# it is statically typed
#
# global number variable
Line 1,818:
a[] = [ 2.1 3.14 3 ]
#
# i is local, because it is first used in the function
for i
print a[i]
.
.
foo
#
# string
Line 1,832:
# array of strings
fruits$[] = [ "apple" "banana" "orange" ]
print fruits$[]
</syntaxhighlight>
=={{header|Eiffel}}==
Variables must be declared before their use with an explicit type.
<
class
APPLICATION
Line 1,860 ⟶ 1,861:
a: ARRAY[INTEGER]
</syntaxhighlight>
In this example, i and s have local scope and a has global scope. Two variables of the same class cannot have the same name, regardless of scope.
Global variables are considered class features and follow the same export status modifiers as normal features.
Line 1,870 ⟶ 1,871:
Assignment to variables depends on the type of variable
<
-- assume A and B are of the same datatype
B := A
A.some_modification_feature
</syntaxhighlight>
For reference type variables, B copies the reference of A, so any modifications to A (or B) affects the other. In the case of expanded types, B will copy A (memory-wise copy) so any modification to A (or B) will never be seen by the other.
Line 1,883 ⟶ 1,884:
Global declarations:
<
sum x y = x + y</
Local declarations:
<
sum x y = z
where z = x + y</
=={{header|Elena}}==
ELENA 5.0:
<
public program()
Line 1,907 ⟶ 1,908:
c := b + a; // assigning variable
}</
=={{header|Erlang}}==
Variables spring into life upon assignment, which can only happen once (single assignment). Their scope is only the local function and they must start with a capital letter.
<syntaxhighlight lang="erlang">
two() ->
A_variable = 1,
A_variable + 1.
</syntaxhighlight>
=={{header|F Sharp|F#}}==
Variables in F# bind a name to a value and are, by default, immutable. They can be declared nearly anywhere and are normally local to the block/assembly they are defined in. They are declared in the form: let ''name'' ''parameters'' = ''expression''.
<
let mutable y = "mutable" // Mutable string
let recordType = { foo : 6; bar : 6 } // Record
let intWidget = new Widget<int>() // Generic class
let add2 x = 2 + x // Function value</
Types are normally inferred from the values they are initialised with. However, types can be explicitly specified using ''type annotations''.
<
let genericEqual x y : 'a = x = y</
Mutable variables are set using the <code><-</code> operator.
<syntaxhighlight lang
=={{header|Factor}}==
The SYMBOL bit defines a new symbol word which is used to identify variables. use-foo shows how one would modify and get the contents of the variable. named-param-example is an example of using :: to define a word with named inputs, similar to the way other languages do things. Last, but not least, local-example shows how to use [let to define a group of lexically scoped variables inside of a word definition.
<
: use-foo ( -- )
Line 1,944 ⟶ 1,945:
a b + number>string print ;
: local-example ( -- str ) [let "a" :> b "c" :> a a " " b 3append ] ;</
=={{header|Falcon}}==
<
/* partially created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
Line 1,974 ⟶ 1,975:
/* There are plenty more
data types in Falcon */
</syntaxhighlight>
=={{header|Forth}}==
=== Local Variables ===
Historically, Forth has preferred open access to the parameter stack over named local variables. The 1994 standard however added a cell-sized local variable facility and syntax. The semantics are similar to VALUEs: locals are initialized from stack contents at declaration, the name retrieves the value, and TO sets the value of the local name parsed at compile time ("value TO name").
<
LOCALS| b a | \ note: reverse order from the conventional stack comment
b b * a a * + ;</
{{works with|GNU Forth}}
Modern Forth implementations often extend this facility in several ways, both for more convenient declaration syntax and to be more compatible with foreign function interfaces. Curly braces are used to replace the conventional stack comment with a similar looking local variable declaration.
<
a a * b b * + ;</
Modern systems may also allow different local data types than just integer cells.
<
a a F* b b F* F+ c c F* F+ FSQRT ;</
=== Global Variables ===
As mentioned Forth normally uses the parameter stack for input/output arguments. When there is the need for a Global variable Forth simply creates a label and allocates a piece of memory to the variable. When the variable is invoked it does not return the value in the memory but rather it returns the address of the variable on the parameter stack. This is like what other languages call a pointer, however Forth has no such obfuscation. A named memory address is simple to understand. To store a value in the variable the '!' (store) operator is used and to fetch a value from a variable the '@' (fetch) operator is used. VARIABLEs have the same size as the processor's native integer with a minimum size of 16 bits. Double precision variables are created with the word 2VARIABLE that are used with corresponding 2@ and 2! operators.<syntaxhighlight lang="text">VARIABLE X 999 X ! \ create variable x, store 999 in X
VARIABLE Y -999 Y ! \ create variable y, store -999 in Y
2VARIABLE W 140569874. W 2! \ create and assign a double precision variable
</syntaxhighlight>
Test at the Forth Console
<pre>
Line 2,008 ⟶ 2,009:
=={{header|Fortran}}==
<
implicit none
Line 2,036 ⟶ 2,037:
end program test
</syntaxhighlight>
=={{header|FreeBASIC}}==
<br>'''Variable declaration'''<br>
<
or
<
example:
<
Dim x As Double
Dim isRaining As Boolean
Dim As String greeting</
<br>'''Initialization'''<br>
<
Dim var1,var2,... As datatype</
example:
<
Dim realNumber as Double = 3.0
Dim isRaining as Boolean = False
Dim greeting as String = "Hello, this is World speaking."
Dim longArray() As Long = {0, 1, 2, 3}
Dim twoDimensions (1 To 2, 1 To 5) As Integer => {{1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}}</
<br>'''Assignment'''<br>
<
<
d = b^2 - 4*a*c
s3 = s1 & mid(s2,3,2)</
<
<
c -= a
c *= a
Line 2,081 ⟶ 2,082:
c Imp= n
c Or= n
c Xor= n </
<br>'''Standard data types and limits.'''<br>
Line 2,121 ⟶ 2,122:
Declares a variable which is shared between code modules. A matching <tt> Common</tt> statement must appear in all other code modules using the variable.
<
<br>'''Var'''<br>
Declares a variable whose type is implied from the initializer expression.
<
Var variable As datatype
Var var1,var2,... As datatype</
example:
<
Var ii = 6728 '' implicit integer
Var id = 6728.0 '' implicit double</
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
void local fn Variables
dim a as long // dim var as type
dim as long b // dim as type var
long c // 'dim as' is optional
long x, y, z // declarate multiple vars in one line
CFStringRef s1 = @"Alpha", s2 = @"Bravo" // declare and assign in same statement
CFArrayRef array = @[s1,s2] // declare and assign an array
c = 123 // assign
CGRect r = {20,20,120,32} // declare and assign record (struct)
end fn
fn Variables
HandleEvents
</syntaxhighlight>
=={{header|GAP}}==
<
global_var := 1;
Line 2,160 ⟶ 2,179:
IsBound(u[3]);
# false
Unbind(u[4]);</
=={{header|GlovePIE}}==
<
var.end=1
// These variables, respectively, refer to an integer, a boolean, and a string.
Line 2,171 ⟶ 2,190:
// var.example1 now refers to a string object instead.
var.variable1="Bye!"
endif</
=={{header|Go}}==
Line 2,177 ⟶ 2,196:
While Go is statically typed, it provides a “short variable declaration” with no type explicitly stated, as in,
<
This is the equivalent of,
<
x = 3 // assignment</
The technique of not stating the type is known as type inference, or duck typing. The right hand side can be any expression. Whatever type it represents is used as the type of the variable. More examples:
<
same := x == y // same declared as bool
p := &same // type of p is pointer to bool
pi := math.Floor(math.Pi) // math.Floor returns float64, so that is the type of pi</
'''Nothing goes uninitialized'''
Variables declared without initializer expressions are initialized to the zero value for the type.
<
var p *int // initialized to nil</
'''Opposite C'''
Line 2,198 ⟶ 2,217:
Variables can be declared in a list with the keyword var used only once. The syntax visually groups variables and sets the declaration off from surrounding code.
<
x, y int
s string
)</
'''Multiple assignment'''
Multiple values can be assigned in a single assignment statement, with many uses.
<
sinX, cosX = math.Sincos(x) // Sincos function returns two values
// map lookup optionally returns a second value indicating if the key was found.
value, ok = mapObject[key]</
'''Other kinds of local variables'''
Parameters and named return values of functions, methods, and function literals also represent assignable local variables, as in,
<
x++
more = x+x
return
}</
Parameter <tt>x</tt> and return <tt>value</tt> more both act as local variables within the scope of the function, and are both assignable. When the function returns, both go out of scope, although the value of more is then returned as the value of the function.
Line 2,226 ⟶ 2,245:
Short declarations can involve multiple assignment, as in
<
But there are complications involving scope and variables already defined that confuse many programmers new to Go. A careful reading of the language specification is definitely in order, and a review of misconceptions as discussed on the mailing list is also highly recommended.
Line 2,235 ⟶ 2,254:
You can define a variable at the top (module) level or in a <code>where</code>, <code>let</code>, or <code>do</code> construct.
<
f x = x + foobar
Line 2,245 ⟶ 2,264:
f x = do
let foobar = 15
return $ x + foobar</
One particular feature of <code>do</code> notation looks like assignment, but actually, it's just syntactic sugar for the <code>>>=</code> operator and a unary lambda.
<
s <- getLine
print (s, s)
Line 2,255 ⟶ 2,274:
-- The above is equivalent to:
main = getLine >>= \s -> print (s, s)</
''Pattern matching'' allows for multiple definitions of the same variable, in which case each call uses the first applicable definition.
<
funkshun False x = x - 1
foobar = funkshun True 5 + funkshun False 5 -- 6 + 4</
<code>case</code> expressions let you do pattern-matching on an arbitrary expression, and hence provide yet another way to define a variable.
<
[a, b] -> a - b
a : b : c : rest -> a + b - c + sum rest
a -> sum a</
''Guards'' are as a kind of syntactic sugar for if-else ladders.
<
| x < 0 = -1
| otherwise = 0</
A defintion can be accompanied by a ''type signature'', which can request a less general type than the compiler would've chosen on its own. (Because of the monomorphism restriction, there are also some cases where a type signature can request a ''more'' general type than the default.) Type signatures are also useful even when they make no changes, as a kind of documentation.
<
dotProduct ns ms = sum $ zipWith (+) ns ms
-- Without the type signature, dotProduct would
Line 2,288 ⟶ 2,307:
-- Without the type signature, the monomorphism
-- restriction would cause foobar to have a less
-- general type.</
Since Haskell is purely functional, most variables are immutable. It's possible to create mutable variables in an appropriate monad. The exact semantics of such variables largely depend on the monad. For example, <code>STRef</code>s must be explicitly initialized and passed between scopes, whereas the implicit state of a <code>State</code> monad is always accessible via the <code>get</code> function.
=={{header|HicEst}}==
<
! Everything else is 8-byte float, READ/WRITE converts
CHARACTER str="abcdef", str2*345, str3*1E6/"xyz"/
Line 2,325 ⟶ 2,344:
USE Arguments_or_USE : t ! use local object
func = t
END</
=={{header|HolyC}}==
Variables must be declared before use. The declaration of a variable, without assigning a value takes the form <i><typename> <variablename>;</i>
<syntaxhighlight lang
Some common types are: <i>I8, I64, U8, U64, F64</i>.
Line 2,335 ⟶ 2,354:
It is possible to initialize variables with expressions having known values when they are defined.
The syntax follows the form <i><typename> <variablename> = <initializing expression>;</i>
<
U8 b2 = b1 * 10;</
Multiple variables may be defined in a single statement as follows:
<syntaxhighlight lang
To initialized a string:
<
== Icon and Unicon ==
Line 2,348 ⟶ 2,367:
Declarations are confined to scope and use and include local, static, global, procedure parameters, and record definitions. Additionally Unicon has class definitions. Undeclared variables are local by default.
<
procedure main(arglist) # arglist is a parameter of main
Line 2,360 ⟶ 2,379:
# ... rest of program
end</
==={{header|Icon}}===
Line 2,368 ⟶ 2,387:
=={{header|J}}==
<syntaxhighlight lang="j">
val=. 0
</syntaxhighlight>
J has two assignment operators. The =. operator declares, initializes, assigns, etc. a local variable. The =: operator does the same for a "global" variable.
<syntaxhighlight lang="j">
fun =: 3 :0
val1 =: 0
val1 =. 2
Line 2,383 ⟶ 2,405:
0
val2
|value error
</syntaxhighlight>
Note that the language forbids assigning a "global" value in a context where the name has a local definition.
<syntaxhighlight lang="j">
fun1 =: 3 :0
val3=. 0
val3=: 0
)
fun1''
|domain error
</syntaxhighlight>
But the purpose of this rule is to help people catch mistakes. If you have reason to do this, you can easily set up another execution context.
<syntaxhighlight lang="j">
fun2 =: 3 :0
val4=. 0
3 :'val4=:y' y
)
fun2 ''
</syntaxhighlight>
Variables are referred to by name, and exist in locales (which may be used as classes, closures or other stateful references).
Line 2,410 ⟶ 2,437:
=={{header|Java}}==
Variables in Java are declared before their use with explicit types:
<
double b;
AClassNameHere c;</
Several variables of the same type can be declared together:
<syntaxhighlight lang
Variables can be assigned values on declaration or afterward:
<
double b;
int c = 5, d = 6, e, f;
String x = "test";
String y = x;
b = 3.14;</
Variables can have scope modifiers, which are explained [[Scope modifiers#Java|here]].
<code>final</code> variables can only be assigned once, but if they are <code>Object</code>s or arrays, they can be modified through methods (for <code>Object</code>s) or element assignment (for arrays):
<
final String y;
final double[] nums = new double[15];
Line 2,434 ⟶ 2,461:
final Date now = new java.util.Date();
now.setTime(1234567890); //legal
now = new Date(1234567890); //not legal</
=={{header|JavaScript}}==
Line 2,445 ⟶ 2,472:
When resolving a variable, javascript starts at the innermost scope and searches outwards.
<div style='height:30em;width:full;overflow:scroll'><
var a=1;
Line 2,511 ⟶ 2,538:
six();
alert(new Seven().a);
alert(new Seven().b);</
=={{header|Joy}}==
Line 2,519 ⟶ 2,546:
The JOY stack can be initialized:
<syntaxhighlight lang=
'''Assignment'''
Values can be pushed on the stack:
<syntaxhighlight lang=
pushes the value 42 of type integer on top of the stack.
Line 2,530 ⟶ 2,557:
Calling the stack by name pushes a copy of the stack on the stack. To continue the previous example:
<syntaxhighlight lang=
pushes the list [42] on top of the stack. The stack now contains: [42] 42.
=={{header|jq}}==
jq variables are strictly speaking not variable: they are just names given to JSON values. For example, the expression "1 as $x | 2 as $x | $x " can be understood as assigning the value 1 to $x and then assigning another value to $x, with the final result being 2, but it must be understood that the second occurrence of $x shadows the first, so that the third occurrence is just a reference to the second. To see this more clearly, consider the following superficially similar expression:
<
In this case, the expression as a whole yields 1 (rather than 2 as previously), as the subexpression in parentheses does not cause shadowing of the first $x.
Line 2,541 ⟶ 2,568:
In a jq program, variable names are strings beginning with "$" followed by one or more characters chosen from the set of alphanumeric characters augmented with the "_" (underscore) character. Assignment within a jq program is based on the syntax:
<syntaxhighlight lang
This establishes $NAME as a reference to the value of EXPRESSION. There is no special syntax to constrain the type of a variable.
Line 2,547 ⟶ 2,574:
Global variables can be given values on the jq command line. For example, suppose the following two lines are in a file named test.jq:
<
test</
The following invocation:
<
will result in the string "123" being output.
Line 2,563 ⟶ 2,590:
let blocks
type blocks.
<
x::Int32 = 1
#datatypes are inferred dynamically, but can also be set thru convert functions and datatype literals
Line 2,577 ⟶ 2,604:
local x = 1 #assigns 1 to local variable x (used inside scope blocks)
x = 'a' #x is a 'Char' type, designated by single quotes
x = "a" #x is a 1-element string, designated by double quotes</
A common use of variables is giving names to specific, unchanging values. Such variables are only assigned once. This intent can be conveyed to the compiler using the const keyword:
<
const pi = 3.14159265358979323846</
=={{header|Kotlin}}==
Line 2,591 ⟶ 2,618:
Here are some examples of local variables:
<
fun main(args: Array<String>) {
Line 2,616 ⟶ 2,643:
println("$i, $d, $sh, $ch, $bt, $s, $l, $b, $f")
}</
{{out}}
Line 2,625 ⟶ 2,652:
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
1) working in a global scope
Line 2,648 ⟶ 2,675:
} // closing local scope
-> 12
</syntaxhighlight>
=={{header|Lasso}}==
<
var(x)
$x->type // null
Line 2,691 ⟶ 2,718:
'\r'
#copy // unmodified as it used ascopydeep
//array(RADISH, CARROT, CUCUMBER, OLIVE)</
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
'In Liberty BASIC variables are either string or numeric.
'A variable name can start with any letter and it can contain both letters and numerals, as well as dots (for example: user.firstname).
Line 2,724 ⟶ 2,751:
'They can be declared 'global' if such visibility is desired.
'Functions can receive variables by name or by reference.
</syntaxhighlight>
=={{header|Lingo}}==
In Lingo (local) variables are declared by assigning a value:
<
y = "Hello world!"
z = TRUE -- same effect as z = 1</
Trying to use a non declared variable causes a (pre)compile-time error. The following script doesn't compile, but throws "Script error: Variable used before assigned a value":
<
put x
end</
Lingo's value function can be used to "silently" - i.e. without throwing errors - check if a variable is defined or not in the current scope:
<
-- <Void> -- means: undefined</
But variable declarations/assignments can also explicitely assign the constant VOID. The following script compiles successfully, but value("x") would still return <Void>:
<
x = VOID
put x
end</
Global variables are declared by adding "global <varName>" either to the top of a script or anywhere - but before first usage - inside a function body. Both of the following scripts are valid and compile:
<
on foo
put x
end</
<
global x
put x
end</
Global variables can also be declared/created at runtime, by adding them as property to the special _global object:
<
Any other function/script can then access this dynamically created global variable, either by a having a "global <varName>" statement in its code (see above), or by using this special _global object:
<syntaxhighlight lang
=={{header|Logo}}==
Historically, Logo only had global variables, because they were easier to access when stepping through an algorithm. Modern variants have added dynamic scoped local variables.
{{works with|UCB Logo}}
<
name 2 "g2 ; same as make with parameters reversed
global "g3 ; no initial value
Line 2,785 ⟶ 2,812:
print :g4 ; 4
print :L1 ; L1 has no value
print name? "L1 ; false, L1 is not bound in the current scope</
=={{header|LotusScript}}==
<
'a few declarations as example
Dim s as New NotesSession ' declaring a New NotesSession actually returns the current, active NotesSession
Line 2,801 ⟶ 2,828:
End Sub
</syntaxhighlight>
=={{header|Lua}}==
In lua, variables are dynamically typecast, and do not need declaration prior to use.
<
fruit = "banana" -- Here we declare a string datatype
needspeeling = True -- This is a boolean
local b = 2 -- This variable declaration is prefixed with a scope modifier </
The lua programming language supports multiple assignments from within a single statement:
<
=={{header|M2000 Interpreter}}==
Line 2,824 ⟶ 2,851:
<syntaxhighlight lang="m2000 interpreter">
\\ M2000 use inference to state the type of a new variable, at run time
\\ We can use literals of a numeric type
Line 2,920 ⟶ 2,947:
}
If Error or Not Ok then Print Error$ ' we get wrong data type
</syntaxhighlight>
=={{header|Maple}}==
Line 2,926 ⟶ 2,953:
The assignment operator in Maple is := . It is also possible to assign to a variable name using the assign() command. It can also be noted that variables at the top level are global for a given session.
<
print ("a is "||a);
"a is 1"</
Line 2,935 ⟶ 2,962:
A local variable has a smaller scope and can only be used within the procedure it's declared in.
In the following example, b is local to f() and will be 3 within the procedure only. The local variable b does not have a value outside the procedure.
<
f := proc()
local b := 3;
Line 2,944 ⟶ 2,971:
b
"b is 3"
"b is b"</
A global variable has a large scope and can be used anywhere inside a program. A global variable declared outside a procedure can be used within the procedure, and a global variable declared within a procedure can be used outside of it.
In the following example, a is a global variable that is from outside the procedure. The global variable c has a value even when used outside the procedure it was declared in.
<
global c;
c := 3;
Line 2,958 ⟶ 2,985:
"a is 1"
"c is 3"
"c is 3"</
Variables can be reassigned.
<
a := 4:
print ("a is "||a);
"a is 1"
"a is 4"</
Variables can be reassigned as different datatypes.
<
type(a, integer);
a := "Hello World":
Line 2,980 ⟶ 3,007:
"a is Hello World"
false
true</
Variable names may contain spaces and other characters when you enclose them in ``.
<
print(`This is a variable`);
1</
To unassign a variable.
<
type(a, string);
print("c is "||c);
Line 3,003 ⟶ 3,030:
"a is a"
true
"c is c"</
Here, symbol is essentially another term for variable name.
Line 3,059 ⟶ 3,086:
=={{header|MATLAB}} / {{header|Octave}}==
<
s = 'abc'; % string
i8 = int8(5); % signed byte
Line 3,075 ⟶ 3,102:
colvec = [1;2;4]; % column vector
crowvec = [1,2,4]; % row vector
m = [1,2,3;4,5,6]; % matrix with size 2x3</
Variables within functions have local scope, except when they are declared as global
<syntaxhighlight lang
=={{header|Mercury}}==
Line 3,085 ⟶ 3,112:
Variables are normally implicitly instantiated into their natural scope, if not referred to in the head of the rule (as in <code>Name</code> below) and can only be bound once. This feels very similar to Erlang, where variables are function-scoped and single-assignment, without declaration. However, Mercury will reorder code to satisfy data dependencies, so assignments can appear to be out of order:
<
name = Name :-
Name = Title ++ " " ++ Given,
Title = "Dr.",
Given = "Bob".</
Mercury also has state variables, actually pairs of variables, usually instantiated in the head of a rule.
<
greet(Who, !IO) :-
io.write_string("Hello", !IO),
io.format(", %s!\n", [s(Who)], !IO).</
In this example <code>!IO</code> is the state variable, and this code translates to
<
greet(Who, !.IO, !:IO) :-
io.write_string("Hello", !.IO, !:IO),
io.format(", %s!\n", [s(Who)], !.IO, !:IO).</
which translates roughly to:
<
greet(Who, IO0, IO) :-
io.write_string("Hello", IO0, IO1),
io.format(", %s!\n", [s(Who)], IO1, IO).</
<code>!.IO</code> is the bound 'current value' of IO, <code>!:IO</code> is the free 'next value' of IO, and the lexical appearance of these variables matters to their final translation to the normal variables in the third example, where data dependency enforces the intended order of operation (so that "Hello" is always written before the name.)
Line 3,116 ⟶ 3,143:
When state variables are instantiated within a rule, they need explicit instantiation, which you could think of as like a declaration without initialization. The state variable in the following example is existentially quantified, and is used for a temporary string builder:
<
dr(Name) = Titled :-
some [!SB] (
Line 3,124 ⟶ 3,151:
format(handle, " %s", [s(Name)], !SB),
Titled = to_string(!.SB)
).</
Existential vs. universal quantification comes up again to let you make local use of nondeterministic code, as in the following use of a nondeterministic list.member/2.
<
% True if every member of L is less than N
%
:- pred all_under(int::in, list(int)::in) is semidet.
all_under(Limit, L) :-
all [N] (member(N, L) => N < Limit).</
In pure Mercury code that only uses functional data types, and only normal functions in higher-order code, variables can be said to be either 'free' or 'ground' where they're found in code, before the goal they're in changes their instantiation (for example to bind a free variable to a value, making it ground). The only exception are the 'state of the world' values used for I/O, which have 'unique' and 'dead' instantiations.
Line 3,139 ⟶ 3,166:
But as soon as you have higher-order predicates or non-functional data types (and this happens very easily even in rookie code, for example if you use the getopt module to handle command line arguments), then instantiations get more complex. For non-functional data types like arrays this might just mean using some special modes in your rules, but here's an extreme example:
<
:- inst accumulator == (pred(in, out, di, uo) is det).
Line 3,161 ⟶ 3,188:
>> add(-10),
F(0, X, !IO),
io.print_line(X, !IO).</
{{out}}
Line 3,171 ⟶ 3,198:
In that last example all of the insts and modes are just there to make the higher-order code work, so this system might seem like only a chore. It helps though in permitting efficient code with uniqueness, and it lets Mercury not always pay the costs of its logical facilities (there's underlying machinery required for a nondet call, which might be backtracked through, which isn't required in a det call). The variable instantiation system can also be used to provide static guarantees similar to those offered by dependently typed languages; an example of this is the non_empty_list instantiation used by the solutions module. This is getting really advanced, but here's a simple example of instantiation (ab)use:
<
:- interface.
:- import_module io.
Line 3,210 ⟶ 3,237:
SUCCESS_INDICATOR = N == COIN_HEADS;
").
</syntaxhighlight>
Here, <code>print_heads</code> and <code>print_tails</code> take, by type, a coin, which could be either heads or tails, but this code has used the variable instantiation system to insist that they can each only accept one particular value. If you take this code and change the main/2 so that it instead tries to call <code>print_tails(N, !IO)</code>, you'll get a compile-time error. A practical use of this is to avoid having to handle impossible (but well-typed) cases.
Line 3,217 ⟶ 3,244:
Depending on your assembler, variables are either declared in a <code>.data</code> section, or you can use <code>.equ</code> or <code>.definelabel</code> directives to name a specific memory offset. The CPU doesn't (and can't) know the variable's size at runtime, so you'll have to maintain that by using the instructions that operate at the desired length.
<
bar equ foo+1
;it's heavily implied that "foo" is one byte, otherwise, why would you label this? But you should always comment your variables.</
Initialization is done by setting the variable equal to a value. For variables that live entirely in a register, this is very simple:
<
For memory, this is a bit harder.
<
foo equ 0x100 ;represents an offset from USER_RAM. Indexed offsetting can only be done at compile time in MIPS.
la $t0,USER_RAM
nop ;load delay slot ($t0 might not be ready by the time the load occurs)
lbu $t1,foo($t0) ;load the unsigned byte from memory address 0xA0000100</
Variables have no scope, and there is no enforcement of data types. There's nothing stopping you from loading a 32-bit word from an offset that was intended to store a byte. Do so at your own risk.
=={{header|Modula-3}}==
<
IMPORT IO, Fmt;
Line 3,249 ⟶ 3,276:
BEGIN
Foo();
END Foo.</
For procedures, the formal parameters create local variables unless the actual parameter is prefixed by VAR:
<
Here, <tt>n</tt> will be local to the procedure Foo, but if we instead wrote:
<
Then <tt>n</tt> is the global variable <tt>n</tt> (if it exists).
=={{header|Nanoquery}}==
<
//
// variables are initialized when they are defined
Line 3,308 ⟶ 3,335:
// scope using the 'delete' command
test_var = "pretend this is a really large object we want to free up"
delete test_var</
=={{header|Nim}}==
Line 3,347 ⟶ 3,374:
6) Examples
<
var y = 3 # Declaration with type inferred to "int".
Line 3,372 ⟶ 3,399:
proc q =
echo xloc # Referencing a variable in the enclosing scope.</
=={{header|Objeck}}==
Different ways to declare and initialize an integer.
<
a : Int;
b : Int := 13;
c := 7;
</syntaxhighlight>
=={{header|OCaml}}==
Line 3,386 ⟶ 3,413:
The standard way to bind an identifier to a value is the '''let''' construct:
<
This stated, ocaml programmers most often use the word ''variable'' when they refer to bindings, because in the programming world we usually use this word for the default values handlers.
Now to add confusion, real variables also exist in OCaml because it is an ''impure'' functional language. They are called references and are defined this way:
<
References can then be accessed and modified this way:
<
y := 34 (* modification *)</
An identifier can not be declared uninitialised, it is always defined with an initial value, and this initial value is used by the OCaml type inference to infer the type of the binding.
Inside an expression, bindings are defined with the '''let .. in''' construct, and we can also define multiple bindings with the '''let .. and .. in''' construct (here the expression can be the definition of a new identifier or the definition of a function):
<
let a = 31
and b = 150 in
Line 3,407 ⟶ 3,434:
let a = 31
and b = 150 in
(a + b)</
=={{header|Oforth}}==
Line 3,426 ⟶ 3,453:
Using -> removes the top of the stack and assign this value to the variable
<
: testVariable
| a b c |
Date now ->a
a println ;</
=={{header|ooRexx}}==
While REXX (and ooRexx) normally pass arguments ''by value''. ooRexx has a mechanism to pass compound variables ''by reference''.
<syntaxhighlight lang="text">a.=4711
Say 'before sub a.3='a.3
Call sub a.
Line 3,443 ⟶ 3,470:
use Arg a.
a.3=3
Return</
{{out}}
<pre>before sub a.3=4711
Line 3,452 ⟶ 3,479:
Ol is a purely functional Lisp, so there are no variables in common sense in Ol. We use 'symbol' and 'linked value' instead.
<
; Declare the symbol 'var1' and associate number 123 with it.
(define var1 123)
Line 3,474 ⟶ 3,501:
; ==> 321
; ... function 'show' still print old associated value
</syntaxhighlight>
Other possible ways to declare a symbol and link value with it: let, let*, letrec, letrec*, define a function.
Line 3,481 ⟶ 3,508:
=={{header|Openscad}}==
<
mynumber=5+4; // This gives a value of nine
</syntaxhighlight>
=={{header|OxygenBasic}}==
<syntaxhighlight lang="text">
'WAYS OF DECLARING VARIABLES
'AND ASSIGNING VALUES
Line 3,522 ⟶ 3,549:
print p[1] '6
print p[2] '8
</syntaxhighlight>
=={{header|Oz}}==
Line 3,528 ⟶ 3,555:
Oz variables are dataflow variables. A dataflow variable can basically be free (unbound) or determined (has a value). Once a value has been assigned, it can not be changed. If we assign the same value again, nothing happens. If we assign a different value to an already determined variable, an exception is raised:
<
Var %% new variable Var, initially free
{Show Var}
Line 3,534 ⟶ 3,561:
{Show Var}
Var = 42 %% the same value is assigned again: ok
Var = 43 %% a different value is assigned: exception</
In the Emacs-based <em>interactive environment</em>, <code>declare</code> creates a new open scope in which variables can be declared. The variables are visible for the entire rest of the session.
Line 3,541 ⟶ 3,568:
Assignment to dataflow variables is also called unification. It is actually a symmetric operation, e.g. the following binds B to 3:
<
A = 3
B
in
A = B
{Show B}</
However, variables can only be introduced at the left side of the <code>=</code> operator. So this is a syntax error:
<
A = 3
A = B %% Error: variable B not introduced
in
{Show B}</
It is possible to introduce multiple variables in a single statement:
<
[A B C D] = [1 2 3 4] %% unification of two lists</
In a <em>module definition</em>, toplevel variables can be introduced between the keywords <code>define</code> and <code>end</code> without the need for <code>declare</code>. The range between these two keywords is also their scope. Toplevel variables can optionally be exported.
<
export Function
define
Line 3,568 ⟶ 3,595:
42
end
end</
Function and class definitions introduce a new variable with the name of the function/class and assign the new function/class to this variable.
Most Oz statement introduce a new scope and it is possible to introduce local variables at the top of this scope with the <code>in</code> keyword.
<
LocalVar1
in
Line 3,587 ⟶ 3,614:
end
LocalVar1
end</
Here, <code>LocalVar1</code> is visible in the whole body of <code>Function</code> while <code>LocalVar2</code> is only visible in the <code>then</code> branch and <code>LocalVar3</code> is only visible in the <code>else</code> branch.
Additionally, new local variables can be introduced everywhere using the keyword <code>local</code>.
<
{System.showInfo "Here, LocalVar is not visible."}
local
Line 3,598 ⟶ 3,625:
{System.showInfo LocalVar}
end
end</
New variables are also introduced in pattern matching.
<
<code>_</code> creates a new nameless variable that is initially unbound. It is usually pronounced "don't care".
It is possible to create a read-only view of a variable with the <code>!!</code> operator. This is called a "future". We can wait for such a variable to become bound by another thread and we can read its value, but we can never set it.
<
A
B = !!A %% B is a read-only view of A
Line 3,612 ⟶ 3,639:
B = 43 %% this blocks until A is known; then it fails because 43 \= 42
end
A = 42</
Additional operations on variables:
<
V = 42
in
Line 3,624 ⟶ 3,651:
elseif {IsFree V} then %% check whether V is free; not recommended
{Show free}
end</
<code>IsFree</code> and <code>IsDet</code> are low-level functions. If you use them, you code is no longer declarative and prone to race conditions when used in a multi-threaded context.
To have mutable references like in imperative languages, use cells:
<
A = {NewCell 42}
OldVal
Line 3,634 ⟶ 3,661:
{Show @A} %% read a cell with @
A := 43 %% change its value
OldVal = A := 44 %% read and write at the same time (atomically)</
<code>A</code> is an immutable dataflow variable that is bound to a mutable reference.
Line 3,640 ⟶ 3,667:
=={{header|PARI/GP}}==
There are two types of local variables, <code>local</code> (mostly deprecated) and <code>my</code>. Variables can be used without declaration or initialization; if not previously used such a variable is a pure variable: technically, a monomial in a variable with name equal to the variable name. This behavior can be forced with the apostrophe operator: regardless of the value (if any) currently stored in <code>x</code>,
<syntaxhighlight lang
displays as (and is treated internally as) <code>x</code>. This is useful when you want to use it as a variable instead of a number (or other type of object). For example,
<syntaxhighlight lang
is a cubic polynomial, not the number 8, even if x is currently 1.
=={{header|Pascal}}==
See [[Variables#Delphi | Delphi]]
=={{header|PascalABC.NET}}==
Definition of multiple variables with explicit type:
<syntaxhighlight lang="delphi">
var i,j: integer;
</syntaxhighlight>
Definition of a variable with initialization:
<syntaxhighlight lang="delphi">
var n: integer := 5;
</syntaxhighlight>
Definition of a variable with initialization and type inference:
<syntaxhighlight lang="delphi">
var n := 5;
</syntaxhighlight>
Definition of multiple variables with type inference:
<syntaxhighlight lang="delphi">
var (m,x) := (5,4.3);
</syntaxhighlight>
Local and global variables with same names:
<syntaxhighlight lang="delphi">
var i: integer;
procedure p;
begin
var i: integer;
end;
</syntaxhighlight>
It's impossible to use variables with same names in nested lightweight namespaces:
<syntaxhighlight lang="delphi">
var i: integer;
begin
for var i:=1 to 10 do // Error!
Print(i)
end;
</syntaxhighlight>
=={{header|Perl}}==
Line 3,652 ⟶ 3,720:
In perl, variables are global by default and can be manipulated from anywhere in the program. Variables can be used without first being declared, providing that the strict pragmatic directive is not in effect:
<
$fruit='apple';
}
dofruit;
print "The fruit is $fruit";</
Variables can be declared prior to use and may be prefixed with [[scope modifiers]] <code>our</code>, <code>my</code>, or <code>local</code> see [[scope modifiers]] for the differences. Variables which haven't been assigned to have the undefined value by default. The undefined value acts just like <code>0</code> (if used as a number) or the empty string (if used as a string), except it can be distinguished from either of these with the <code>defined</code> function. If warnings are enabled, perl will print a message like "Use of uninitialized value $foo in addition (+)" whenever you use the undefined value as a number or string.
Line 3,663 ⟶ 3,731:
Initialization and assignment are the same thing in Perl: just use the <code>=</code> operator. Note that the rvalue's context (scalar or list) is determined based on the lvalue.
<
# number of elements in @a.
my ($x) = @a; # List assignment; $x is set to the first
Line 3,672 ⟶ 3,740:
# two elements of @a, and @b the rest.
my ($x, $y, @b, @c, $z) = @a; # Same thing, and also @c becomes empty
# and $z undefined.</
The kind of value a variable can hold depends on its sigil, "sigil" being a slang term for "funny character in front of a variable name". <code>$dollarsigns</code> can hold scalars: the undefined value, numbers, strings, or [http://perldoc.perl.org/perlref.html references]. <code>@atsigns</code> can hold arrays of scalars, and <code>%percentsigns</code> can hold hashes of scalars (associative arrays mapping strings to scalars); nested data structures are constructed by making arrays or hashes of references to arrays or hashes.
Line 3,682 ⟶ 3,750:
If the strict pragmatic directive is in effect, then variables need explicit scope declaration, so should be prefixed with a my or our keyword depending on the required level of scope:
<
our $fruit; # declare a variable as global
our $veg = "carrot"; # declare a global variable and define its value</
=== Local and global variables ===
Line 3,690 ⟶ 3,758:
The following example shows the use of local and global variables:
<
sub dofruit {
Line 3,699 ⟶ 3,767:
dofruit;
print "The global fruit is still $fruit";</
=={{header|Phix}}==
Line 3,728 ⟶ 3,796:
Variables must be declared before use, may be assigned on declaration, and can utilise multiple assignment/sequence decomposition, eg:
<!--<
<span style="color: #004080;">integer</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">25</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">25</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">z</span>
<span style="color: #004080;">object</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{},</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"string"</span><span style="color: #0000FF;">}</span>
<!--</
In the latter statement, c is set to "string", b is set to 5, and a is set to {}. (In multiple assignment, values are assigned right-to-left to avoid having to reorder any subscripts.) You could also use
Line 3,742 ⟶ 3,810:
User defined types are declared with a single-parameter function that returns true or false, eg:
<!--<
<span style="color: #008080;">type</span> <span style="color: #000000;">hour</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">>=</span> <span style="color: #000000;">0</span> <span style="color: #008080;">and</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;"><=</span> <span style="color: #000000;">23</span>
Line 3,749 ⟶ 3,817:
<span style="color: #000000;">h1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">10</span> <span style="color: #000080;font-style:italic;">-- ok</span>
<span style="color: #000000;">h2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">25</span> <span style="color: #000080;font-style:italic;">-- error! program aborts with a message</span>
<!--</
Phix has no notion of unsigned numeric types, except via user defined types such as the above which explicitly prevent their use.
Line 3,758 ⟶ 3,826:
=={{header|PHP}}==
<
/**
* @author Elad Yosifon
Line 3,920 ⟶ 3,988:
* @url http://php.net/manual/en/resource.php
*/
</syntaxhighlight>
=={{header|PicoLisp}}==
Line 3,926 ⟶ 3,994:
'[http://software-lab.de/doc/refU.html#use use]' or
'[http://software-lab.de/doc/refL.html#let let]':
<
(setq A 1 B 2 C 3)
... )</
This is equivalent to
<
... )</
The parentheses can be omitted if there is only a single variable
<
(setq A ..)
... )
(let A 1
...)</
Other functions that handle local bindings are
'[http://software-lab.de/doc/refL.html#let? let?]',
Line 3,947 ⟶ 4,015:
=={{header|PL/I}}==
<
declare i float; /* external, global variable, excluded from the */
Line 3,968 ⟶ 4,036:
q = 0; /* run-time initialization of all elements of Q to zero. */
q = r; /* run-time assignment of all elements of array R to */
/* corresponding elemets of S. */</
=={{header|Pony}}==
<
let temp: F64 = 36.6 // immutable variable 'temp'
let str: String // immutable variable 'str' with no initial value
Line 3,978 ⟶ 4,046:
let b = true
let b' = false // variable names can contain ' to make a distinct variable with almost the same name</
Destructive read
<
var y: I32 = x = 20
try
Fact(x == 20) // x gets the new value of 20
Fact(y == 10) // y gets the old value of x which is 10
end</
=={{header|PowerShell}}==
Variables in PowerShell start with a $ character, they are created on assignment and thus don't need to be declared:
<
$i = 123</
Uninitialized variables expand to nothing. This may be interpreted for example as an empty string or 0, depending on context:
<
"abc" + $foo + "def" # yields "abcdef"</
Variables all show up in the '''Variable''': drive and can be queried from there with the usual facilities:
<syntaxhighlight lang
Since Variables are provided via a flat filesystem, they can be manipulated using the common cmdlets for doing so. For example to delete a variable one can use
<syntaxhighlight lang
as if it were a file or a registry key. There are, however, several cmdlets dealing specifically with variables:
<
New-Variable # creates a new variable
Set-Variable # sets the value of a variable
Clear-Variable # deletes the value of a variable, but not the variable itself
Remove-Variable # deletes a variable completely</
=={{header|Prolog}}==
Variables in imperative languages are, in essence, named memory locations where items of data can be stored. Prolog, as a declarative language, has no variables in this sense, and therefore has no way of declaring them or assigning to them. Prolog variables are more like variables in formal logic or in mathematics. Here is a very simple Prolog program:
<
man(socrates).</
The symbol <tt>:-</tt> may be read as 'when' or 'if', so that the first line is equivalent to the statement in predicate logic ∀<i>x</i>: <i>px</i> → <i>qx</i> where <i>px</i> is interpreted as '<i>x</i> is a man' and <i>qx</i> is interpreted as '<i>x</i> is mortal'. Prolog notation, however, requires variable names to start with (or consist of) a capital letter: this is how the interpreter knows that <tt>socrates</tt> is not a variable.
We can of course use more than one variable:
<
taught(socrates,plato).</
When we put queries to the Prolog system, it will seek to find a consistent set of interpretations that allows our query to be true in the light of the facts and rules we have provided:
<
yes
?- student(X,socrates).
X=plato
?- student(socrates,X).
no</
And so forth. We can reuse the same variable names in different statements as much as we like, but within each statement the same variable must be capable of referring to the same term.
<
no</
Prolog does not answer like that because it is a connoisseur of the mythology; and in any case several ancient writers report that Zeus's tomb could be seen on Crete. But the rule states that <tt>X</tt> is mortal if <tt>X</tt>—the same <i>x</i>—is a man, so it could only unify successfully if <tt>zeus</tt> and <tt>socrates</tt> were the same (which even his most devoted admirers did not claim). If our original rule had said
<
then the two variables would be able to refer to two different terms, and the Prolog interpreter would agree that <tt>mortal(zeus)</tt>.
=={{header|PureBasic}}==
<
Debug a
; or value "" for a string, they are not case sensitive
Line 4,076 ⟶ 4,144:
; In constrast to variables, a constant has no types except an (optional) $ sign to mark it as string constant
#Float_Constant = 2.3
; Maps, LinkedLists , Arrays and Structures are not handled here, because they are no elemental variables</
=={{header|Python}}==
Line 4,083 ⟶ 4,151:
Names in global statements are looked up in the outermost context of the program or module. Names in a nonlocal statement are looked up in the order of closest enclosing scope outwards.
<
# these examples, respectively, refer to integer, float, boolean, and string objects
example1 = 3
Line 4,092 ⟶ 4,160:
# example1 now refers to a string object.
example1 = "goodbye"
</syntaxhighlight>
=={{header|Quackery}}==
Line 4,162 ⟶ 4,230:
=={{header|R}}==
Variables are dynamically typed, so they do not need to be declared and instantiated separately. <- and = are both used as the assignment operator, though <- is preferred, for compatibility with S-Plus code.
<
bar = "abc"</
It is possible to assign multiple variables with the same value, and to assign values from left to right.
<
TRUE -> quuux</
There are also global assignment operators, <<- and ->>. From their help page:
The operators '<<-' and '->>' cause a search to made through the
Line 4,174 ⟶ 4,242:
place in the global environment.
In practice, this usually means that variables are assigned in the user workspace (global environment) rather than a function.
<
assignmentdemo <- function()
Line 4,188 ⟶ 4,256:
message(paste("in the global environment, a = ", get("a", envir=globalenv())))
}
assignmentdemo()</
assign 'a' locally, i.e. within the scope of the function
inside assignmentdemo, a = 5
Line 4,196 ⟶ 4,264:
in the global environment, a = 7
Finally, there is also the assign function, where you choose the environment to assign the variable.
<
assign("c", runif(10), envir=globalenv()) #equivalent to c <<- runif(10)</
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
Line 4,248 ⟶ 4,316:
;; racket, structs that are extensions of other structs,
;; pattern-matching on structs, classes, and much more)
</syntaxhighlight>
=={{header|Raku}}==
Line 4,258 ⟶ 4,326:
Assigning an array to a scalar variable now makes that scalar variable a reference to the array:
<syntaxhighlight lang="raku" line>
my @y = <A B C D>; # Array of strings 'A', 'B', 'C', and 'D'
say @y[2]; # the @-sigil requires the container to implement the role Positional
Line 4,278 ⟶ 4,346:
say "this is quite bad"; # but then string interpolation
say "this is quite {bad}" # becomes more wordy
</syntaxhighlight>
Laziness is a big topic in Raku. Sometimes Raku programmers are so lazy, they can't even be bothered with giving [http://design.raku.org/S02.html#Names_and_Variables variables names].
<syntaxhighlight lang="raku"
say ++$; # this is a different anonymous state variable, prefix:<++> forces it into numerical context and defaults it to 0
say $+=2 for 1..10; # here we do something useful with another anonymous variable
sub foo { $^a * $^b } # for positional arguments we often can't be bothered to declare them or to give them fancy names
say foo 3, 4;</
{{output}}
Line 4,302 ⟶ 4,370:
=={{header|Rascal}}==
The effect of a variable declaration is to introduce a new variable Name and to assign the value of expression Exp to Name. A variable declaration has the form
<
A mention of Name later on in the same scope will be replaced by this value, provided that Name’s value has not been changed by an intermediate assignment. When a variable is declared, it has as scope the nearest enclosing block, or the module when declared at the module level.
Line 4,308 ⟶ 4,376:
As a convenience, also declarations without an initialization expression are permitted inside functions (but not at the module level) and have the form
<syntaxhighlight lang
and only introduce the variable Name.
Line 4,320 ⟶ 4,388:
Two explicit variable declarations:
<
int: 100
rascal>min = 0;
int: 0</
An implicit variable declaration
<
>>>>>>> <"thu", 4>, <"fri", 5>, <"sat",6>, <"sun",7>};
rel[str, int]: {
Line 4,336 ⟶ 4,404:
<"fri",5>,
<"sun",7>
}</
Variable declaration and assignment leading to type error
<
int: 12
rascal>month ="December";
|stdin:///|(7,10,<1,7>,<1,17>): Expected int, but got str</
Pitfalls
Local type inference for variables always uses the smallest possibe scope for a variable; this implies that a variable introduced in an inner scope is not available outside that scope. Here is how things can go wrong:
<
str: "abc"
rascal>x;
|stdin:///|(0,1,<1,0>,<1,1>): Undeclared variable, function or constructor: x</
=={{header|REXX}}==
Line 4,364 ⟶ 4,432:
To assign some data (value) to a variable, one method is to use the assignment operator, an equal sign (<big>'''='''</big>):
<
bb = '' /*assigns a null value ───► BB */
cc = 2*10 /*assigns chars 20 ───► CC */
Line 4,373 ⟶ 4,441:
hh = "+10" /*assigns chars +10 ───► hh */
ii = 1e1 /*assigns chars 1e1 ───► ii */
jj = +.1e+2 /*assigns chars .1e+2 ───► jj */</
Variables '''aa, ff, gg, hh, ii,''' and '''jj''' will all be considered ''numerically equal'' in REXX (but not exactly equal ''except'' for '''ff''' and '''gg''').
===assignments via PARSE===
<
kk = 'dead beaf'X /*assigns hex deadbeaf ───► KK */
ll = '0000 0010'b /*assigns blank ───► LL (ASCII) */
Line 4,394 ⟶ 4,462:
cat = 'A cat is a lion in a jungle of small bushes.'
/*assigns a literal ───► CAT */</
===assignments via VALUE===
Assignments can be made via the '''value''' BIF ['''B'''uilt-'''I'''n '''F'''unction] (which also has other capabilities), the
<br>capability used here is to create a variable name programmatically (normally using concatenation or abuttal).
<
/*assigns a literal ───► CAT */
yyy='CA'
Line 4,406 ⟶ 4,474:
yyy = 'CA'
call value yyy || 'T', "Honest as the Cat when the meat's out of reach."
/*assigns a literal ───► CAT */</
===unassigned variables===
There are methods to catch unassigned variables in REXX.
<
signal on noValue /*usually, placed at pgm start. */
Line 4,429 ⟶ 4,497:
say badSource
say
exit 13</
Note: the value (result) of the '''condition''' BIF can vary in different implementations of a REXX interpreter. <br>
Line 4,451 ⟶ 4,519:
REXX subroutines/functions/routines/procedures can have their own "local" variables if the '''procedure''' statement is used.
<br>Variables can be shared with the main program if the variables are named on the '''procedure''' statement with the '''expose''' keyword.
<
q = 55 ; say ' 1st q=' q /*assign a value ───► "main" Q.*/
call sub ; say ' 2nd q=' q /*call a procedure subroutine. */
Line 4,468 ⟶ 4,536:
sand: /*all REXX variables are exposed.*/
q = "Monty" ; say 'sand q=' q /*assign a value ───► "global" Q*/
return</
'''output'''
<pre>
Line 4,483 ⟶ 4,551:
===default value for an array===
There is a way in REXX to assign a default value (or an initial value, if you will) to a (stemmed) array.
<
aaa.1=1 /*assign 1 to first element.*/
aaa.4=4. /* " 4 " fourth " */
Line 4,489 ⟶ 4,557:
do j=0 to 8 /*go through a bunch of elements.*/
say 'aaa.'||j '=' aaa.j /*display element # and its value*/
end /*we could've started J at -100.*/</
===dropping a variable===
Line 4,498 ⟶ 4,566:
<br>for the REXX language (or for that matter, not even specified), but it's apparently what all (Classic) REXX
<br>interpreters do at the the time of this writing.
<
say 'radius =' radius
drop radius /*now, "undefine" the variable. */
say 'radius =' radius</
Note: The value of an undefined (or deallocated) REXX variable is the uppercased name of the REXX variable name. <br>
Line 4,517 ⟶ 4,585:
variables' values (which can be any string) with the constants
and the intervening periods.
<
x='3 '
var.x.x.4='something else'
Line 4,523 ⟶ 4,591:
a=left(i,2)
Say i var.a.a.4 "(tail is '"a||'.'||a||'.'||'4'"')"
End</
Output:
<pre>
Line 4,537 ⟶ 4,605:
Syntax:
<
<Variable Name> = <Value>
</syntaxhighlight>
The operator ‘=’ is used here as an Assignment operator and the same operator can be used in conditions, but for testing equality of expressions.
Line 4,547 ⟶ 4,615:
Ring is a dynamic programming language that uses Dynamic Typing.
<
x = "Hello" # x is a string
see x + nl
Line 4,564 ⟶ 4,632:
x = false # x is a number (logical value = 0)
see x + nl
</syntaxhighlight>
We can use the assignment operator ‘=’ to copy variables. We can do that to copy values like strings & numbers. Also, we can copy complete lists & objects. The assignment operator will do a complete duplication for us. This operation called Deep Copy
<
list = [1,2,3,"four","five"]
list2 = list
Line 4,575 ⟶ 4,643:
See "********" + nl
See list2 # print the second list - contains 5 items
</syntaxhighlight>
Ring is a weakly typed language, this means that the language can automatically convert between data types (like string & numbers) when that conversion make sense.
Line 4,581 ⟶ 4,649:
Rules:
<
<NUMBER> + <STRING> --> <NUMBER>
<STRING> + <NUMBER> --> <STRING>
</syntaxhighlight>
The same operator ‘+’ can be used as an arithmetic operator or for string concatenation.
<
x = 10 # x is a number
y = "20" # y is a string
Line 4,594 ⟶ 4,662:
Msg = "Sum = " + sum # Msg is a string (sum will be converted to a string)
see Msg + nl
</syntaxhighlight>
=={{header|RPL}}==
A global variable is declared with the <code>STO</code> instruction after the variable name.
A local variable, which disappears at end of execution, is declared with the <code>→</code> instruction before the variable name, which is idiomatically in lowercase.
in both cases, the variable is initialized with the value at stack level 1, whatever its type.
123 'V' STO
123 → v
A new value can then be assigned with the <code>STO</code> instruction:
"AZ" 'V' STO
"AZ" 'v' STO
A variable can contain any type of data, which can change without need for reinitialization, as shown above.
It is possible to add, substract, multiple, divide... the content of stack level 1 to a variable with specific instructions, resp. <code>STO+, STO-, STO*, STO/</code>...
If the variable contains a list, STO+ will append or prepend the content of stack level 1, according to the order of the arguments:
456 'MYLIST' STO+ <span style="color:grey">@ prepend</span>
'MYLIST' 456 STO+ <span style="color:grey">@ append</span>
<code>STO-</code> and <code>STO/</code> have the same versatility:
123 'V' STO- <span style="color:grey">@ V ← 123 - V</span>
'V' 123 STO- <span style="color:grey">@ V ← V - 123</span>
=={{header|Ruby}}==
Line 4,617 ⟶ 4,703:
Referencing an undefined global or instance variable returns <code>nil</code>. Referencing an undefined local variable throws a <code>NameError</code> exception.
<
class Demo
@@a_class_var = 6
Line 4,627 ⟶ 4,713:
@an_instance_var += a_local_var
end
end</
=={{header|Rust}}==
In Rust a variable needs to be declared before it is used. A variable is declared using the "let" command. Some common data types are: i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64, bool, char and String. Rust is strongly typed and strictly typed, however the Rust compiler can infer the data types based on how the variable is used. Therefore there are several different options for variable declaration:
<syntaxhighlight lang="rust">
let var01; // The compiler will infer the type or the compiler will ask for type annotations if the type can't be inferred
let var02: u32; // The compiler will check if a value is assigned to var02 before being used
let var03 = 5; // The compiler will infer the type or it will fallback to i32
let var04 = 5u8; // Initialization to unsigned 8 bit (u8) number 5
let var05: i8 = 5; // Type annotation + Initialization
let var06: u8 = 5u8; // Type annotation + Initialization
var01 = var05; // This line makes the compiler infer var01 should be a signed 8 bit number (i8).
var02 = 9u32; // Assigning to var02 after declaration
</syntaxhighlight>
Variables are immutable by default. So all the above declarations will all create an immutable variable that can't be reassigned once assigned for the first time. To make the variable mutable you need to add the "mut" keyword like in the following examples:
<syntaxhighlight lang="rust">
let mut var07;
let mut var08: f32;
let mut var09 = 1.5;
let mut var10 = 2.5f32;
let mut var11: f32 = 5.0;
let mut var12: f64 = 5.0f64;
var07 = var11; // This line makes the compiler infer var07 should be a f32.
var08 = 3.1416f32; // Assigning to var08 after declaration
var08 = 2.7183f32; // Reassigning var08 since it can be reassigned since it is mutable.
</syntaxhighlight>
The compiler emits a warning if a variable is not used. To suppress the warning, you need to put an underscore "_" prefix before the variable name:
<syntaxhighlight lang="rust">
let _notused = 10;
let mut _mutnotused = 42;
</syntaxhighlight>
=={{header|Scala}}==
Line 4,641 ⟶ 4,758:
Seed7 variables must be defined with type and initialization value, before they are used.
There are global variables and variables declared local to a function.
<
var integer: foo is 5; # foo is global
Line 4,655 ⟶ 4,772:
begin
aFunc;
end func;</
=={{header|Set lang}}==
There is no declared intialization of variables, or datatypes. '''Set''' already initializes 52 variables, named a-z with a value of 0 (ASCII for Null) each, and A-Z with ASCII values corresponding to their characters (65-90). There is also a question mark variable, which represents the number of the current line of code being executed.
<
set b 66 > Simple variable assignment - ''b'' is now the ASCII value of 66, or the character 'B'
[c=0] set c 5 > Conditional variable assignment - If ''c'' is 0, then set ''c'' to 5
Line 4,670 ⟶ 4,787:
set e (d+1) > Combiners are defined inside round brackets - () - and have an addition and a subtraction function
set f (e-1) > Variable ''e'' was assigned to ''d'' + 1 (65 + 1 = 66, character B), and ''f'' was assigned to ''e'' - 1 (66 - 1 = 65, character A)
</syntaxhighlight>
=={{header|smart BASIC}}==
Line 4,678 ⟶ 4,795:
Numeric variables can contain real and complex numbers.
<
y = 0.4E3
z = 3-2i</
String variables use the dollar symbol ($) at the end.
<
String values may include the quotation symbol " by specifying double quotes "".
<
===Initialization===
Line 4,694 ⟶ 4,811:
Variables are initialized when assigned as either numeric or strings. However, smart BASIC in unique in that it will automatically interpret a numeric value from a string if utilized in that manner.
<
a$ = "6 feet"
PRINT n * a$</
{{out}}
<pre>
Line 4,708 ⟶ 4,825:
Arrays are DIM-ensioned by default with a size of 10. Larger arrays must be pre-DIM-entioned.
<syntaxhighlight lang
===Assignment===
Line 4,720 ⟶ 4,837:
===Scope===
All variables are local in smart BASIC. Variables within the main program are localized from variables within defined functions as well as other defined functions. However, variables may be accessed outside of their localized areas by preceding the variable with the function name and a period. By extension, the main program scope is null, therefore non-function variables may be accessed within functions with a period before the variable and a null scope (for example: .x).
<
MyF2 = x^2
MyF3 = x^3
MyFunction = MyF2 + MyF3
END DEF</
To access the variables within the function:
<
PRINT x; MyFunction.MyF2; MyFunction.MyF3</
Variables may also be made global using the DEF command:
<
=={{header|SNOBOL4}}==
Line 4,737 ⟶ 4,854:
Local variables in Snobol are declared in a function definition prototype string:
<
foo a = 1; b = 2; c = 3
foo = a * ( x * x ) + b * y + c :(return)
foo_end</
This defines a function foo( ) taking two arguments x,y and three localized variables a,b,c. Both the argument parameters and vars are dynamically scoped to the function body, and visible to any called functions within that scope. The function name also behaves as a local variable, and may be assigned to as the return value of the function. Any variable initialization or assignment is done explicitly within the function body. Unassigned variables have a null string value, which behaves as zero in numeric context.
Line 4,753 ⟶ 4,870:
In SPL variables are autodeclared according to their usage. For example, this one-line program is valid because it is evident what is expected:
<
In contrast, this one-line program raises an error because it is not evident what object "a" is:
<
'''Assignment.'''
<
b,c,d = 0</
'''Datatypes.'''
Line 4,772 ⟶ 4,889:
An object can become a reference to another object using "~" symbol, for example:
<
a = 3
#.output(r)
r = 5
#.output(a)</
{{out}}
Line 4,791 ⟶ 4,908:
=={{header|SuperCollider}}==
Variables are always local to the scope of a closure or an object.
<syntaxhighlight lang="supercollider">
// variable declaration
var table, chair;
Line 4,862 ⟶ 4,979:
~y = { SinOsc.ar(440, 0, 0.1) }; // and a sine tone
</syntaxhighlight>
=={{header|Swift}}==
<
// All variables declared outside of a struct/class/etc are global
Line 4,935 ⟶ 5,052:
myFunc = showScopes // myFunc is now showScopes
myFunc() // foo bar function</
=={{header|Tcl}}==
Line 4,941 ⟶ 5,058:
Demonstrating:
<
# Define a procedure with two formal arguments; they are local variables
proc bar {callerVarName argumentVar} {
Line 4,963 ⟶ 5,080:
unset argumentVar
}
}</
The main thing to note about Tcl is that the "<tt>$</tt>" syntax is a language level operator for reading a variable and not just general syntax for referring to a variable.
Line 4,972 ⟶ 5,089:
Variables may be assigned with the <code>→</code> to a value.
<
:1→A
</syntaxhighlight>
=={{header|TI-89 BASIC}}==
Line 4,980 ⟶ 5,097:
A variable not declared local (to a program or function) is global. Global variables are grouped into ''folders'' of which one is current at any given time. Global variables persist until deleted (or reset or power loss, unless they are ''archived'').
<syntaxhighlight lang
Variables may be assigned with the <code>→</code> or <code>Define</code> statements, both of which assign a new value to a variable. <code>→</code> is typically used interactively, but only <code>Define</code> can assign programs or multi-statement functions.
<
1 → mynum
Line 4,996 ⟶ 5,113:
Return x
EndIf
EndFunc</
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT,{}
var1=1, var2="b"
Line 5,015 ⟶ 5,132:
PRINT var,"=",@var
ENDLOOP
</syntaxhighlight>
Output:
<pre>
Line 5,031 ⟶ 5,148:
Simple example: the <code>cases</code>
<
hey @a
how are you
Line 5,037 ⟶ 5,154:
hey @b
long time no see
@(end)</
This directive has two clauses, matching two possible input cases, which have a common first line. The semantics of cases is short-circuiting: the first successful clause causes it to succeed and stop processing subsequent clauses. Suppose that the input matches the second clause. This means that the first clause will also match the first line, thereby establishing a binding for the variable <code>a</code>. However, the first clause fails to match on the second line, which means that it fails. The interpreter then moves to the second clause, which is tried at the original input position, under the original binding environment which is devoid of the <code>a</code> variable. Whichever clause of the <code>cases</code> is successful will pass both its environment modifications and input position increment to the next element of the query.
Under some other constructs, environments may be merged:
<
@a bar
@(or)
foo @b
@(end)</
The <code>maybe</code> directive matches multiple clauses such that it succeeds no matter what, even if none of the clauses succeed. Clauses which fail have no effect, but the effects of all successful clauses are merged. This means that if the input which faces the above <code>maybe</code> is the line <code>"foo bar"</code>, the first clause will match and bind <code>a</code> to foo, and the second clause will also match and bind <code>b</code> to bar. The interpreter integrates these results together and the environment which emerges has both bindings.
Line 5,052 ⟶ 5,169:
=={{header|uBasic/4tH}}==
uBasic/4tH has two kinds of variables, 26 predefined global integer variables (named <b>A</b> to <b>Z</b>) and a maximum of 26 parameters/local integer variables (named <b>A@</b> to <b>Z@</b>). The latter aren't defined, but merely allocated, using <b>LOCAL(</b><i>n</i><b>)</b> or <b>PARAM(</b><i>n</i><b>)</b>. The first allocated local variable is assigned <b>A@</b>, the second <b>B@</b>, etc. Both parameters and local variables are freed after <b>RETURN</b>. Parameters are always passed by value.
<syntaxhighlight lang="text">' Initialization
A = 15 ' global variable
Line 5,071 ⟶ 5,188:
A@ = 5 ' reassignment of parameter A@
B@ = 23 ' local variable
Return</
=={{header|UNIX Shell}}==
Line 5,077 ⟶ 5,194:
{{works with|Bourne Shell}}
<syntaxhighlight lang="sh">
#!/bin/sh
# The unix shell uses typeless variables
Line 5,084 ⟶ 5,201:
pears = `expr 5+4` # We use the external expr to perform the calculation
myfavourite="raspberries"
</syntaxhighlight>
=={{header|Ursa}}==
<
#
# declare [type] [name]
Line 5,129 ⟶ 5,246:
# variables are referenced by their name
decl port p
out p endl console</
=={{header|VBA}}==
Line 5,215 ⟶ 5,332:
<br>'''Variable declaration'''<br>
<
Dim var1,var2,... As datatype</
example:
<
Dim x as Double
Dim isRaining as Boolean
Dim greeting as String</
<br>'''Initialization'''<br>
<
Dim var1,var2,... As datatype</
example:
<
Dim realNumber as Double = 3.0
Dim isRaining as Boolean = False
Dim greeting as String = "Hello, this is World speaking."
Dim longArray() As Long = {0, 1, 2, 3}
Dim twoDimensions(,) As Integer = {{0, 1, 2}, {10, 11, 12}}</
<br>'''Assignment'''<br>
<
<
d = b^2 - 4*a*c
s3 = s1 & mid(s2,3,2)</
<
<
c -= a
c *= a
Line 5,247 ⟶ 5,364:
c <<= n
c >>= n
c &= a</
<br>'''Data types'''<br>
Line 5,280 ⟶ 5,397:
Attributes <code>Public</code> or <code>Private</code> can mofidy these scopes.
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">name := 'Bob'
age := 20
large_number := i64(9999999999)</
Variables are declared and initialized with :=. This is the only way to declare variables in V. This means that variables always have an initial value.
Line 5,293 ⟶ 5,410:
'''Mutable variables'''
<syntaxhighlight lang="v (vlang)">mut age := 20
println(age) // 20
age = 21
println(age) // 21</
To change the value of the variable use =. In V, variables are immutable by default. To be able to change the value of the variable, you have to declare it with mut.
Line 5,303 ⟶ 5,420:
The values of multiple variables can be changed in one line. In this way, their values can be swapped without an intermediary variable.
<syntaxhighlight lang="text">mut a := 0
mut b := 1
println('$a, $b') // 0, 1
a, b = b, a
println('$a, $b') // 1, 0</
'''Declaration errors'''
In development mode the compiler will warn you that you haven't used the variable (you'll get an "unused variable" warning). In production mode (enabled by passing the -prod flag to v – v -prod foo.v) it will not compile at all (like in Go).
<syntaxhighlight lang="v (vlang)">fn main() {
a := 10
if true {
Line 5,316 ⟶ 5,433:
}
// warning: unused variable `a`
}</
Unlike most languages, variable shadowing is not allowed. Declaring a variable with a name that is already used in a parent scope will cause a compilation error.
Line 5,323 ⟶ 5,440:
WDTE does not have variables, per se, but it does have several things that work similarly. The most obvious is function parameters:
<
The parameters are scoped to the inside of the function in which they're declared. There are also lambdas, which also have parameters:
<
Lambdas are closures, so they have access to the parameters of the function that called them. The above multiplies 3 by the value of t.
Line 5,333 ⟶ 5,450:
There are also 'slots' for chains. Chains are essentially a series of expressions that are all 'chained' together. They take advantage of the fact that everything in WDTE is a function. In a chain, the first is called, then the second, and then the return of the second is called with the return of the first as an argument, then the third is called, and then its return is called with the output of the previous segment, and so on. In each element of the chain, a 'slot' can be specified which serves as a named binding for accessing that element's return value later. For example:
<
file.open name : f
-> str.format '{}' data
-> io.writeln f
-- io.close f
;</
In this example, first <code>file.open name</code> is called. After this, the return value of that call can be accessed later in the chain using <code>f</code>. This is done in the last element as a way of closing the file.
Line 5,344 ⟶ 5,461:
Finally, an expression can also be bound to a name using a <code>let</code> expression, like in the function declarations shown above, as assigning a value to a function with no parameters is similar to creating a constant. When a <code>let</code> is encountered, all following expressions in the current block of code are run under a subscope of the current scope, which gives much the same effect as a variable assignment. For example:
<
io.writeln io.stdout a;</
=={{header|Wren}}==
Line 5,357 ⟶ 5,474:
Here are a few examples.
<
a = 1 // initializes 'a'
a = "a" // assigns a different value to 'a'
Line 5,371 ⟶ 5,488:
}
System.print(d) // prints the value of the top level 'd'
System.print(e) // compiler error : Variable is used but not defined</
=={{header|XPL0}}==
Line 5,406 ⟶ 5,523:
=={{header|XSLT}}==
Although called variables, XSLT "variable" elements are single-assignment, and so behave more like constants. They are valid in the node scope in which they are declared.
<
<xsl:if test="$foo = 4">... </xsl:if> <!-- prepend '$' to reference a variable or parameter--></
=={{header|Z80 Assembly}}==
Like in [[6502 Assembly]], variables need not be declared per se. Any memory location can be given a label and a value can be stored at that memory location and retrieved from it.
<
ld a,&50 ;load hexadecimal 50 into A
Line 5,417 ⟶ 5,534:
ld a,&40 ;load hexadecimal 40 into A
ld (UserRam),a ;assign UserRam a new value of &40</
Z80 has two data types: byte and word. Words are little-endian, meaning that the "low byte" is stored first. The two statements below are identical:
<
word &BEEF</
Bytes can be loaded into 8-bit registers, and words can be loaded into 16-bit register pairs. A value can be treated as a pointer to a memory location by enclosing it in brackets, which dereferences the pointer before loading from it:
<
ld hl,TestData ;H = &90, L = &00
Line 5,437 ⟶ 5,554:
org &9000
TestData:
byte &EF,&BE</
Scope does not exist in Z80 Assembly by default, unless enforced by the assembler itself. Assemblers that do not support local labels will require all labels to be unique.
Line 5,443 ⟶ 5,560:
=={{header|zkl}}==
The are two variable type in zkl, register (auto in C) and var (instance variable). vars are global to class [instance], registers are visible to their scope and enclosed scopes. In addition, a function can have vars (static var in C), which are actually [hidden] instance data. vars have no type.
<
class C{ var v } // global to class C, each instance gets a new v
class C{fcn f{var v=123;}} // v can only be seen by f, initialized when C is
Line 5,456 ⟶ 5,573:
v acts like a property to run f so C.v is the same as C.f()
class C{reg r} // C.r is compile time error
r:=5; // := syntax is same as "reg r=5", convenience</
Line 5,468 ⟶ 5,585:
=={{header|Zoea}}==
<
# The concept of variables is completely alien in zoea:
# there is no support for variables and no way of defining or using them.
# Instead programs are described by giving examples of input and output values.
</syntaxhighlight>
=={{header|Zoea Visual}}==
|