Variables: Difference between revisions

118,860 bytes added ,  1 month ago
m
m (→‎{{header|360 Assembly}}: Superfluous blanks suppressed)
 
(142 intermediate revisions by 58 users not shown)
Line 13:
<br><br>
 
=={{header|11l}}==
To declare <code>a</code> as an integer:
<syntaxhighlight lang="11l">Int a</syntaxhighlight>
 
Type of variables may be inferred:
<syntaxhighlight lang="11l">V a = 1</syntaxhighlight>
 
Multiple variables may be defined in a single line as follows:
<syntaxhighlight lang="11l">Int p, a, d</syntaxhighlight>
=={{header|360 Assembly}}==
;assignment, reference, referencing:
<langsyntaxhighlight lang="360asm">* value of F
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</langsyntaxhighlight>
;declarations, initialization, datatypes:
<langsyntaxhighlight lang="360asm">* declarations length
C DS C character 1
X DS X character hexa 1
Line 45 ⟶ 54:
SI DC CL12'789' string 12
PI DC PL16'7' packed decimal 16
ZI DC ZL32'7' zoned decimal 32</langsyntaxhighlight>
;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:
<syntaxhighlight lang="6502asm"> org $1200
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!</syntaxhighlight>
 
 
 
Each example below is equivalent, but which one you use depends on the assembler.
 
The <code>equ</code> method:
<syntaxhighlight lang="6502asm">joystick equ $00 ;this variable is located at zero page memory address $00
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</syntaxhighlight>
 
The <code>enum</code> method:
<syntaxhighlight lang="6502asm">enum $0000
;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
Player_Xpos dsb 1
Player_Ypos dsb 1
pointer dsb 2 ;this takes up 2 bytes
sound_on dsb 1
ende ;end enumeration</syntaxhighlight>
 
The <code>rs</code> method:
<syntaxhighlight lang="6502asm">.rsset $0000
joystick .rs 1
Player_Xpos .rs 1
Player_Ypos .rs 1
pointer .rs 2
sound_on .rs 1
;no closer needed for this method</syntaxhighlight>
 
===Initialization===
This mostly depends on the hardware you are programming for. If the code runs in RAM, you can initialize an entire block of RAM to the value of choice with <code>ds <count>,<value></code> (replace count and value with numbers of your choice, no arrow brackets.) On systems like the NES which have dedicated RAM areas on the CPU and the whole program is in ROM, you're best off setting all RAM to zero on startup and initializing the ram to the desired values at runtime.
 
===Assignment===
Assignment is done by storing values into memory. Variables larger than 8 bits will need to be loaded in pieces.
<syntaxhighlight lang="6502asm">LDA #$05
STA Player1_Lives ;equivalent C code: Player1_Lives = 5;
 
LDA #$05
STA pointer+1
LDA #$40
STA pointer
;loads the variable pointer with the value $0540</syntaxhighlight>
 
===Datatypes===
The 6502 can only handle one data type natively: 8 bit. Anything larger will need to be represented by multiple memory locations. Since the CPU is little-endian the low byte should be "first," i.e. if you have a variable declared such as <code>pointer dsb 2</code> then the low byte must be stored in <code>pointer</code> and the high byte in <code>pointer+1</code>. (You do not declare <code>pointer+1</code> separately; the assembler will take <code>pointer+1</code> to mean the memory address directly after <code>pointer</code>. The 6502 uses consecutive zero-page memory locations as a means of indirect addressing.)
 
===Scope===
The 6502 has no concept of scope; every variable is global. Assemblers can enforce scope rules to allow the reuse of labels you would want to use frequently, like "skip," "continue," "done," etc., but normally each label can't be defined more than once in the same program. You can trick the assembler into (effectively although not technically) letting you re-use the same label with bank switching but for the most part each label must be unique.
 
===Referencing===
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.
 
<syntaxhighlight lang="6502asm">NametableBase equ $20 ;label referring to a constant
VRAM_ADDR equ $2006 ;label referring to a memory address
VRAM_DATA equ $2007 ;label referring to a memory address
 
LDA #NametableBase ;without a # this is interpreted as a memory address like any other number would be.
STA VRAM_ADDR
LDA #$00
STA VRAM_ADDR
 
LDA #$03
STA VRAM_DATA</syntaxhighlight>
 
=={{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.
 
<syntaxhighlight lang="68000devpac">MyVar:
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.</syntaxhighlight>
 
=={{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.
 
<syntaxhighlight lang="asm">.data
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]</syntaxhighlight>
 
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.
 
<syntaxhighlight lang="asm">Player1_Lives equ 0100h
mov al,3
mov byte ptr [Player1_Lives],al ;give the player 3 lives to start the game with</syntaxhighlight>
 
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:
 
<syntaxhighlight lang="asm"> mov ax, seg MyData ;the assembler replaces this with the segment MyData is located in prior to assembling the program.
mov ds,ax ;load this segment into the data segment register.</syntaxhighlight>
 
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.
 
=={{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:
<langsyntaxhighlight lang="forth">
\ declare a variable which is initialized to the number '0'
var x
Line 63 ⟶ 180:
\ Change the cat to a dog:
"dog" y !
</syntaxhighlight>
</lang>
 
=={{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 */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szString: .asciz "String définition"
sArea1: .fill 11, 1, ' ' // 11 spaces
// or
sArea2: .space 11,' ' // 11 spaces
cCharac: .byte '\n' // character
cByte1: .byte 0b10101 // 1 byte binary value
hHalfWord1: .hword 0xFF // 2 bytes value hexa
.align 4
iInteger1: .int 123456 // 4 bytes value decimal
iInteger3: .short 0500 // 4 bytes value octal
iInteger5: .int 0x4000 // 4 bytes value hexa
 
iInteger7: .word 0x4000 // 4 bytes value hexa
iInteger6: .int 04000 // 4 bytes value octal
TabInteger4: .int 5,4,3,2 // Area of 4 integers = 4 * 4 = 16 bytes
dDoubleInt1: .quad 0xFFFFFFFFFFFFFFFF // 8 bytes value hexa
dfFLOAT1: .double 0f-31415926535897932384626433832795028841971.693993751E-40 // Float 8 bytes
sfFLOAT2: .float 0f-31415926535897932384626433832795028841971.693993751E-40 // Float 4 bytes (or use .single)
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sBuffer: .skip 500 // 500 bytes values zero
iInteger2: .skip 4 // 4 bytes value zero
dDoubleint2: .skip 8 // 8 bytes value zero
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdriInteger2 // load variable address
mov x1,#100
str x1,[x0] // init variable iInteger2
100: // standard end of the program
mov x0, 0 // return code
mov x8, EXIT // request to exit program
svc 0 // perform the system call
qAdriInteger2: .quad iInteger2 // variable address iInteger2
 
</syntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">Name: declare -- a local declaration block has an optional name
A : constant Integer := 42; -- Create a constant
X : String := "Hello"; -- Create and initialize a local variable
Line 73 ⟶ 255:
function F (X: Integer) return Integer is
-- Inside, all declarations outside are visible when not hidden: X, Y, Z are global with respect to F.
X: Integer := Z; -- hides the outer X which however can be referedreferred to by Name.X
begin
...
Line 84 ⟶ 266:
...
end;
end Name; -- End of the scope</langsyntaxhighlight>
 
=={{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 ="algol68">int j;</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="algol68">LONG REAL double1, double2, double3;</langsyntaxhighlight>
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>
<langsyntaxhighlight lang="algol68">SHORT INT b1 := 2500;
LONG INT elwood = 3*bsize, jake = bsize -2;</langsyntaxhighlight>
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 ="algol68">FLEX[20]CHAR mystring;</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="algol68">[]CHAR mytext = "The ALGOL 68 Language";</langsyntaxhighlight>
There are more rules regarding arrays, variables containing pointers, dynamic allocation,
and initialization that are too extensive to cover here.
Line 119 ⟶ 301:
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:
<langsyntaxhighlight lang="algolw">% declare some variables %
integer a1, a2; real b; long real c; complex d; long complex f;
logical g; bits h; string(32) j;
Line 126 ⟶ 308:
f := d := c := b := a2 := a1 := 0; % multiple assignment %
g := false; h := #a0; j := "Hello, World!";
</syntaxhighlight>
</lang>
 
Records can be declared, composed of fields of the basic types and references to records. E.g.:
<langsyntaxhighlight lang="algolw">record R1 ( integer length; string(256) text );
reference(R1) ref1, ref2;</langsyntaxhighlight>
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.:
<langsyntaxhighlight lang="algolw">record person( string(32) name; integer age );
record date( integer day, month, year );
reference(person, date) ref3;</langsyntaxhighlight>
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.:
<langsyntaxhighlight lang="algolw">reference(integer) refInt; % an illegal declaration %</langsyntaxhighlight>
The following could be used instead:
<langsyntaxhighlight lang="algolw">record INT_VALUE ( integer val );
reference(INT_VALUE) refInt;</langsyntaxhighlight>
 
Fields are referedreferred to via a function-like notation, e.g.:
<langsyntaxhighlight lang="algolw">% using the person record defined above...%
reference (person) someone;
someone := person % create a new person structure with uninitialised fields %
Line 150 ⟶ 332:
age(someone) := 27;
% could also initialise the fields when the record is created: %
someone := person( "Harry", 32 );</langsyntaxhighlight>
 
Arrays of the basic types and references can also be declared, but records cannot contain arrays.
Line 157 ⟶ 339:
 
=={{header|Apex}}==
<syntaxhighlight lang="apex">
<lang Apex>
// If not initialized at class/member level, it will be set to null
Integer x = 0;
Line 173 ⟶ 355:
Boolean b = true;
AClassName cls = new AClassName();
</syntaxhighlight>
</lang>
 
=={{header|AppleScript}}==
Variables are untyped in AppleScript, but they must be instantiated before use.
Example:<syntaxhighlight lang AppleScript="applescript">set x to 1</langsyntaxhighlight>
Scope may be explicitly defined before instantiation using either the <code>global</code> or <code>local</code> declarations.<langsyntaxhighlight AppleScriptlang="applescript">global x
set x to 1
local y
set y to 2</langsyntaxhighlight>If undeclared, AppleScript will automatically set the scope based on the following rule: variables declared at the top level of any script will be (implicit) globals, variables declared anywhere else will be (implicit) locals. Scope cannot be changed after being explicitly or implicitly defined.
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:<langsyntaxhighlight AppleScriptlang="applescript">on localx()
set x to 0 -- implicit local
return x
Line 197 ⟶ 379:
return {localx(), globalx()}
end run
--> RETURNS: {0, 1}</langsyntaxhighlight>
 
Applescript also supports top-level entities known as <code>properties</code> that are global to that script.
Example:<syntaxhighlight lang AppleScript="applescript">property x : 1</langsyntaxhighlight>Properties behave exactly as global variables except that they are persistent. Their most recent values are retained between script executions (or until the script is recompiled).
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program variable.s */
/************************************/
/* Constantes Définition */
/************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
szString: .asciz "String définition"
sArea1: .fill 11, 1, ' ' @ 11 spaces
@ or
sArea2: .space 11,' ' @ 11 spaces
 
cCharac: .byte '\n' @ character
cByte1: .byte 0b10101 @ 1 byte binary value
 
hHalfWord1: .hword 0xFF @ 2 bytes value hexa
.align 4
iInteger1: .int 123456 @ 4 bytes value decimal
iInteger3: .short 0500 @ 4 bytes value octal
iPointer1: .int 0x4000 @ 4 bytes value hexa
@ or
iPointer2: .word 0x4000 @ 4 bytes value hexa
iPointer3: .int 04000 @ 4 bytes value octal
 
TabInteger4: .int 5,4,3,2 @ Area of 4 integers = 4 * 4 = 16 bytes
 
iDoubleInt1: .quad 0xFFFFFFFFFFFFFFFF @ 8 bytes
 
dfFLOAT1: .double 0f-31415926535897932384626433832795028841971.693993751E-40 @ Float 8 bytes
sfFLOAT2: .float 0f-31415926535897932384626433832795028841971.693993751E-40 @ Float 4 bytes (or use .single)
 
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sBuffer: .skip 500 @ 500 bytes values zero
iInteger2: .skip 4 @ 4 bytes value zero
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdriInteger2 @ load variable address
mov r1,#100
str r1,[r0] @ init variable iInteger2
 
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdriInteger2: .int iInteger2 @ variable address iInteger2
 
</syntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">num: 10
str: "hello world"
 
arrA: [1 2 3]
arrB: ["one" "two" "three"]
arrC: [1 "two" [3 4 5]]
arrD: ["one" true [ print "something" ]]
 
dict: [
name: "john"
surname: "doe"
function: $[][
print "do sth"
]
]
 
inspect symbols</syntaxhighlight>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">x = hello ; assign verbatim as a string
z := 3 + 4 ; assign an expression
if !y ; uninitialized variables are assumed to be 0 or "" (blank string)
Line 212 ⟶ 478:
global y ;
static z=4 ; initialized once, then value is remembered between function calls
}</langsyntaxhighlight>
 
=={{header|AWK}}==
===Dynamic variables===
<langsyntaxhighlight lang="awk">BEGIN {
# Variables are dynamically typecast, and do not need declaration prior to use:
fruit = "banana" # create a variable, and fill it with a string
Line 235 ⟶ 501:
print "a,b,c=",a,b,c, "c+0=", c+0, 0+c
print "a+b=", a+b, "b+c=", b+c
}</langsyntaxhighlight>
{{Out}}
<pre>
Line 249 ⟶ 515:
===Assignment on commandline===
It is possible to assign value to variables from the commandline:
<langsyntaxhighlight lang="awk"># usage: awk -v x=9 -f test.awk
BEGIN {
y = 3
Line 255 ⟶ 521:
print "x,y,z:", x,y,z
printf( "x=%d,y=%d,z=%d:", x,y,z )
}</langsyntaxhighlight>
{{Out}} with "-v x=9":
<pre>
Line 274 ⟶ 540:
by listing the variable as an additional dummy function argument
after the required arguments:
<langsyntaxhighlight lang="awk">function foo(s, k) {
# s is an argument passed from caller
# k is a dummy not passed by caller, but because it is
Line 288 ⟶ 554:
foo(s,k)
print "k still is", k
}</langsyntaxhighlight>
{{Out}}
<pre>
Line 306 ⟶ 572:
* NF is the number of fields
*$NF is the contents of the last field.
<langsyntaxhighlight lang="awk"># Feeding standard-input with echo:
echo -e "2 apples 0.44$ \n 3 banana 0.33$" | awk '{p=$1*$NF; sum+=p; print $2,":",p; }; END{print "Sum=",sum}'</langsyntaxhighlight>
With more data, this would look like
awk '{p=$1*$NF; sum+=p; print $2,":",p; }; END{print "Sum=",sum}' inputfile
Line 322 ⟶ 588:
 
In Axe, variables are global because they are (mostly) static references to memory locations. This means there is also no scope.
<syntaxhighlight lang ="axe">1→A</langsyntaxhighlight>
 
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 ="axe">#Realloc(L₂)</langsyntaxhighlight>
 
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 335 ⟶ 601:
In BASIC, variables are global and there is no scope. However, it is an error to reference a variable before it has been assigned.
 
<langsyntaxhighlight lang="gwbasic">10 LET A=1.3
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 350 ⟶ 616:
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</langsyntaxhighlight>
 
==={{header|Applesoft BASIC}}===
 
In Applesoft BASIC, variables are global and there is no scope. And, it is not an error to reference a variable before it has been assigned.
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.
 
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic"> 10 A = 1.7: REM LET IS NOT REQUIRED
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 371 ⟶ 637:
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.</langsyntaxhighlight>
 
==={{header|Commodore BASIC}}===
In Commodore BASIC, variables are global and there is no scope, and as with other BASIC dialects, it is not an error to reference a variable before it has been assigned.
 
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.
 
'''Naming and Data Types'''
 
A variable can be uniquely identified with a maximum of two (2) alpha-numeric characters, and the first must be a letter. The type of variable is identified with either a <code>%</code> or <code>$</code> or no symbol at all. Certain reserved words that are two characters long cannot be used as variables (e.g. <code>TO</code>, <code>ON</code>, etc.)
 
{| class="wikitable"
!Symbol !! Variable Type
|-
| (none) || Floating point number
|-
| % || Integer number
|-
| $ || String
|}
 
There are functions available to convert between number and string types.
 
'''Comparison of Variables'''
 
All variables, including strings, can be compared using the comparitive operators <code>&lt;</code>,<code>&gt;</code>, and <code>=</code>. '''Note:''' String comparison follows character order in Commodore PETSCII, that is, '''A''' is less than '''<span style="font-size: 140%; line-height: 50%;">&spades;</span>''' in uppercase/graphics mode, while '''A''' is greater than '''a''' in mixed case mode. Conventional ASCII would have '''a''' greater than '''A'''.
 
'''Arrays'''
 
Arrays can be used for any of the above types. In other dialects of BASIC, it may be necessary to initialize an array with the DIM command before any use, however in Commodore BASIC, one and two dimensional arrays of up to 11 elements (index 0 through 10) in one or both dimensions may be used without any initial DIMensioning. Any array larger than 11 elements in either dimension, or more than two dimensions of any size, '''''must''''' be initialized with <code>DIM</code> prior to use.
 
In theory, arrays can be of any size, however BASIC memory limits must be observed. For example, a single dimension string array of 256 elements (0 through 255) would theoretically occupy ALL of the Commodore 64's 64 kilobytes of RAM... 255 elements each holding 255 bytes of string data. However, only a little under 40 kilobytes is available in all of the default BASIC RAM space, which must be shared for program storage as well as runtime variable storage.
 
With each of the three data types, and including the possibility of arrays, <code>a</code>, <code>a%</code>, <code>a$</code>, <code>a(0)</code>, <code>a%(0)</code>, and <code>a$(0)</code> represent at least six (6) unique variables, plus any additional elements which might be part of the array definitions.
 
'''Demonstration Program'''
 
<syntaxhighlight lang="gwbasic">1 rem rosetta code
5 rem commodore basic variable demonstration
10 print chr$(147);chr$(14);:ti$="000000":rem see lines 420-460
15 rem numeric variables default to 0; strings default to empty
20 print a:print b%:print c$:print
25 :
30 rem no symbol after variable defaults to float.
35 let a=1.7
40 rem "let" is not required and rarely used.
45 b=2.42
50 print a:print b
55 rem % means integer type; digits after decimal are truncated
60 b%=1.7
65 print b%
70 rem $ means string type
75 c$="Commodore"
80 print c$:print
85 :
90 rem each type is unique, even when name is "same"
95 a=5.0
100 a%=9
105 a$="twenty-five"
110 print a:print a%:print a$:print
115 :
120 rem names unique only to two characters; extra ignored
125 li=10:lives=8:lights=64
130 print li:print lives:print lights:print
135 rem second character can be alphanumeric, but is not array
140 s1=100 : s2=200 : s3=300
145 print s1:print s2:print s3:print
150 gosub 5000
155 :
160 rem strings preserve all literal characters
165 rem numerics drop leading zeros and trailing zeros after decimal
170 n$="01276":print n$:rem 01276
175 o%=01276:print n%: rem 1276
180 p=4.900:print p: print: rem 4.9
185 :
190 rem string-numeric conversion functions
195 c$="05034"
200 c%=val(c$) : rem converts to the numeric value of 5034 (first zero dropped)
205 d=123.45600 : rem define a float
210 d$=str$(d) : rem converts above into a string
215 print c$:print c%:print d:print d$:print
218 :
220 rem strings can be ordered/compared > or < like numbers
225 input "Enter a string";x$:print
230 input "Enter another string";y$:print
235 if x$>y$ then print x$;" comes after ";y$
240 if x$<y$ then print x$;" comes before ";y$
245 if x$=y$ then print "You entered the same string twice!"
250 gosub 5000
255 :
260 rem numbers have a leading character for pos/neg sign
265 rem " " means positive
270 a=-52:b=124
275 print a:print b:print
280 :
285 rem variable operations
290 e$="endothermic":print e$
295 print left$(e$,3) : rem "end"
300 print right$(e$,3) : rem "mic"
305 print mid$(e$,4,5) : rem "other"
310 print
315 a=5:b=20:c=a+b:print a;"+";b;"=";c : rem addition
320 q=90:r=60:s=q-r:print s : rem subtraction
325 x=3:y=4:z=x*y:print x;"*";y;"=";z : rem 12 multiplication
330 l=12:m=16:n=l/m:print l;"/";m;"=";n :rem division
335 rem string concatenation
340 print
345 f$="John":l$="Jones":n$=l$+", "+f$:print f$:print l$:print n$
350 gosub 5000
355 :
360 rem arrays can be single or multidimensional
365 rem array index starts at 0
370 rem single dimenstion arrays of 11 elements or less
375 rem do not need to be DIMensioned
380 a$(0)="first":a$(1)="second":a$(3)="third":rem we skipped index 2
385 for i=0 to 3:print a$(i):next
390 gosub 5000
395 dim b(1,20) : rem 42 elements
400 for i=0 to 1:for j=0 to 20:b(i,j)=(i+1)*j:next j,i
405 for i=0 to 1:print chr$(19):for j=0 to 20:print tab(i*6);b(i,j):next j,i
410 gosub 5000
415 :
420 rem special variables - ti and st are technically functions,
425 rem but ti$ can be assigned a value similar to a string variable
430 t$=left$(ti$,2)+":"+mid$(ti$,3,2)+":"+right$(ti$,2)
435 print "Ticks since program started:":print ti
440 print "Elapsed time since program started:":print t$
445 print "I/O Status:";st : rem i/o status
450 print:print "Enter new time (HHMMSS): ";:gosub 5200
455 ti$=t$:gosub 5500
460 print
465 :
470 rem all variables can be cleared with the "clr" statement
475 rem however, this also clears the return address stack for subroutines
480 rem making "return" not possible.
485 print "Before CLR:":print a:print a$:print a$(0):print b:print c
490 clr:print:print "After CLR:"
495 print a:print a$:print a$(0):print b:print c
500 print
505 end
600 :
700 rem supporting subroutines
800 :
5000 rem screen pause routine
5005 print:print "press a key to continue"
5010 get k$:if k$="" then 5010
5015 print chr$(147):return
5020 :
5200 rem custom time input routine
5205 t$="":for d=1 to 6
5210 get k$:if k$<"0" or k$>"9" then 5210
5215 t$=t$+k$:print k$;:next
5220 return
5230 :
5500 rem display live clock
5505 print chr$(147):print:print "Press a key to continue."
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</syntaxhighlight>
 
'''Modifications for Enhanced TIME$'''
 
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):
 
<syntaxhighlight lang="gwbasic">10 print chr$(147);chr$(14);:ti$="0000000":rem see lines 420-460
 
430 t$=left$(ti$,2)+":"+mid$(ti$,3,2)+":"+mid$(ti$,5,2)+"."+right$(ti$,1)
 
5205 t$="":for d=1 to 7
 
5500 rem display live clock
5505 print chr$(147):print:print "Press a key to continue."
5510 t$=left$(ti$,2)+":"+mid$(ti$,3,2)+":"+mid$(ti$,5,2)+"."+right$(ti$,1)
5515 print chr$(19);"Time: "t$
5520 get k$:if k$="" then 5510
5525 print chr$(147);:return</syntaxhighlight>
 
==={{Header|Tiny BASIC}}===
<syntaxhighlight lang="tiny basic">REM Tiny Basic has exactly 26 variables.
REM They start off initialised to zero.
PRINT A
 
REM The only data type is sixteen-bit signed integer.
REM They are assigned using the LET statement.
REM Their scope is the whole program.
LET B = -12345
REM The integer arithmetic operations of + - * and / can be used
REM and so can the unary negative and positive operators - +
LET C = 1 + B - B/5
LET A = -B
PRINT "B is ", B
PRINT "C is ", C
GOSUB 10
 
REM The comparison operators = < > <= >= <> are available,
REM but their results are not expressions and can only be used in an
REM if statement.
LET D = 3
IF D <> 7 THEN LET D = 7
GOTO D-2
PRINT "Skip this"
5 PRINT "Gotos and gosubs can be computed. Beware of moving spaghetti."
END
10 PRINT "B is now ", B
RETURN
 
REM Tiny Basic does not support arrays or pointers. Strings can
REM be used, but only as string constants within a PRINT statement.</syntaxhighlight>
 
=={{header|Batch File}}==
Batch file variables are not limited to data types and they do not need to be initialized before use.
 
<langsyntaxhighlight lang="dos">
@echo off
 
Line 394 ⟶ 866:
set myString
pause>nul
</syntaxhighlight>
</lang>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> REM BBC BASIC (for Windows) has the following scalar variable types;
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 430 ⟶ 902:
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.</langsyntaxhighlight>
 
=={{header|Bracmat}}==
<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.
<lang bracmat>(myfunc=i j.!arg:(?i.?j)&!i+!j)</lang>
Global variables are created the first time they are assigned a value.
 
<strong>Initialization.</strong>
Local variables are initialised to <code>0</code>.
 
<strong>Assignment.</strong>
There are two ways.
 
To assign unevaluated code to a variable, you normally would use the <code>&lt;<i>variable</i>>=&lt;<i>unevaluated expression</i>></code> syntax.
 
To assign an evaluated expression to a variable, you use pattern matching as in <code>&lt;<i>evaluated expression</i>>:?&lt;<i>variable</i>></code>
 
<strong>Datatypes.</strong> There are no datatypes. The nature of an expression is observed by pattern matching.
 
<strong>Scope.</strong> Local variables have dynamic scope.
 
<strong>Referencing.</strong> Variables are referenced using the <code>!&lt;<i>variable</i>></code> syntax.
 
<strong>Other variable related facilities.</strong>
Global variables (name as well as value) can be removed from memory with the built-in <code>tbl</code> function.
The names of built-in functions such as <code>put</code> and <code>lst</code> can be used as variable names without adverse effects on the built-in function. It is not possible to redefine built-in functions to do something different.
 
=={{header|Boo}}==
Line 512 ⟶ 958:
 
bool: True or False
 
=={{header|BQN}}==
 
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="bqn">a ← 10</syntaxhighlight>
 
Variables can be modified using the <code>↩</code> symbol after they are declared.
 
BQN uses lexical scoping, where scopes correspond roughly to the blocks they are contained in. A more detailed description can be found in the scoping [https://mlochbaum.github.io/BQN/doc/lexical.html documentation] or [https://mlochbaum.github.io/BQN/spec/scope.html specification].
 
Name matching is case-insensitive, and ignores underscores. While any name can store any value, each instance of a name has a syntactic role determined by BQN's spelling rules:
* A name with a subject role if it starts with a lowercase letter.
* A name with a function role starts with an uppercase letter.
* A name with a 1-modifier role starts with an underscore, and doesn't end with an underscore.
* A name with a 2-modifier role starts with an underscore, and ends with an underscore.
 
=={{header|Bracmat}}==
<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.
<syntaxhighlight lang="bracmat">(myfunc=i j.!arg:(?i.?j)&!i+!j)</syntaxhighlight>
Global variables are created the first time they are assigned a value.
 
<strong>Initialization.</strong>
Local variables are initialised to <code>0</code>.
 
<strong>Assignment.</strong>
There are two ways.
 
To assign unevaluated code to a variable, you normally would use the <code>&lt;<i>variable</i>>=&lt;<i>unevaluated expression</i>></code> syntax.
 
To assign an evaluated expression to a variable, you use pattern matching as in <code>&lt;<i>evaluated expression</i>>:?&lt;<i>variable</i>></code>
 
<strong>Datatypes.</strong> There are no datatypes. The nature of an expression is observed by pattern matching.
 
<strong>Scope.</strong> Local variables have dynamic scope.
 
<strong>Referencing.</strong> Variables are referenced using the <code>!&lt;<i>variable</i>></code> syntax.
 
<strong>Other variable related facilities.</strong>
Global variables (name as well as value) can be removed from memory with the built-in <code>tbl</code> function.
The names of built-in functions such as <code>put</code> and <code>lst</code> can be used as variable names without adverse effects on the built-in function. It is not possible to redefine built-in functions to do something different.
 
=={{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 ="c">int j;</langsyntaxhighlight>
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 ="c">double double1, double2, double3;</langsyntaxhighlight>
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>
<langsyntaxhighlight lang="c">short b1 = 2500;
long elwood = 3*BSIZE, jake = BSIZE -2;</langsyntaxhighlight>
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 ="c">char mystring[21];</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="c">const char * mytext = "The C Language";</langsyntaxhighlight>
There are more rules regarding arrays, variables containing pointers, dynamic allocation,
and initialization that are too extensive to cover here.
 
=={{header|C sharp|C#}}==
Variables in C# are very dynamic, in the form that they can be declared practically anywhere, with any scope.
As in other languages, often used variables are: int, string, double etc.
 
They are declared with the type first, as in C:
<syntaxhighlight lang="csharp">int j;</syntaxhighlight>
 
Multiple variables may be defined in a single line as follows:
<syntaxhighlight lang="csharp">int p, a, d;</syntaxhighlight>
 
It is also possible to assign variables, either while declaring or in the program logic:
<syntaxhighlight lang="csharp">int a = 4;
int b;
int c = Func(a);
 
b = 5;</syntaxhighlight>
 
=={{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="cpp">int a;</syntaxhighlight>
From C++11, type of variables may be inferred:
<syntaxhighlight lang="cpp">auto a = 1; // int a = 1</syntaxhighlight>
 
Template variables are specified with template parameters in angle brackets after the class name:
<syntaxhighlight lang="cpp">std::vector<int> intVec;</syntaxhighlight>
 
=={{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</langsyntaxhighlight>
 
Array variables use a subscript as an element index.<br />
Line 544 ⟶ 1,058:
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>
</lang>
 
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>
</lang>
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>
</lang>
 
=={{header|ChucK}}==
Much like C or C++, declared but not initialized:
<syntaxhighlight lang="text"> int a; </langsyntaxhighlight>
Multiple declaration:
<syntaxhighlight lang="text">int b,c,d; </langsyntaxhighlight>
Declared and initialized:
<syntaxhighlight lang="text">0 => int e;</langsyntaxhighlight>
 
=={{header|C++Clojure}}==
Clojure allows global variable declaration and initialization with '''def''' and the macros that expand into it (e.g. '''defn''', '''defmacro'''). In Clojure, this is known as 'interning a var'. Clojure encourages immutable programming, but often does not enforce it: '''def''' and most of its related forms can be used successfully more than once with the same symbol in the same namespace, although this is considered bad style. A vast majority of real-world Clojure uses the '''def''' forms for global scope, and '''let'''-like bindings ('''loop''', '''for''', '''doseq''') for local scope. Clojure provides options such as '''alter-var-root''' and '''with-redefs''' for more advanced use.
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 ";".
<lang cpp>int a;</lang>
 
'''Declaration only:'''
Template variables are specified with template parameters in angle brackets after the class name:
<syntaxhighlight lang="lisp">(declare foo)</syntaxhighlight>
<lang cpp>std::vector<int> intVec;</lang>
<syntaxhighlight lang="lisp">(def bar)</syntaxhighlight>
 
'''Global scope initialization:'''
=={{header|C sharp|C#}}==
<syntaxhighlight lang="lisp">(def foo 42)</syntaxhighlight>
Variables in C# are very dynamic, in the form that they can be declared practically anywhere, with any scope.
<syntaxhighlight lang="lisp">(defonce bar 42)</syntaxhighlight>
As in other languages, often used variables are: int, string, double etc.
<syntaxhighlight lang="lisp">(defn baz [x] 42)</syntaxhighlight>
<syntaxhighlight lang="lisp">(defmacro qux [x] 42)</syntaxhighlight>
 
'''Local scope initialization:'''
They are declared with the type first, as in C:
<syntaxhighlight lang="lisp">(let [foo 42] ...)</syntaxhighlight>
<lang csharp>int j;</lang>
 
'''Local re-binding of dynamic global var:'''
Multiple variables may be defined in a single line as follows:
<syntaxhighlight lang="lisp">(def ^:dynamic foo 10)
<lang csharp>int p, a, d;</lang>
(binding [foo 20] ...)</syntaxhighlight>
 
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:
It is also possible to assign variables, either while declaring or in the program logic:
<syntaxhighlight lang="lisp">(defn len [^String x]
<lang csharp>int a = 4;
(.length x))</syntaxhighlight>
int b;
int c = Func(a);
 
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.
b = 5;</lang>
<syntaxhighlight lang="lisp">(def foo (atom 42))</syntaxhighlight>
<syntaxhighlight lang="lisp">(def bar (ref 42))</syntaxhighlight>
<syntaxhighlight lang="lisp">(def baz (agent 42))</syntaxhighlight>
 
=={{header|COBOL}}==
Line 600 ⟶ 1,118:
===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.
<langsyntaxhighlight lang="cobol">MOVE 5 TO x
MOVE FUNCTION SOME-FUNC(x) TO y
MOVE "foo" TO z
MOVE "values 1234" TO group-item
SET some-index TO 5</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="cobol">01 normal-date.
03 year PIC 9(4).
03 FILLER PIC X VALUE "-".
Line 624 ⟶ 1,142:
MOVE "2012-11-10" TO normal-date
MOVE CORR normal-date TO reversed-date
DISPLAY reversed-date *> Shows '10-11-2012'</langsyntaxhighlight>
 
===Declaration===
Line 638 ⟶ 1,156:
 
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:
<langsyntaxhighlight lang="cobol">01 a PIC X(20). *> a is a string of 20 characters.
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.</langsyntaxhighlight>
 
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 648 ⟶ 1,166:
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.
<langsyntaxhighlight lang="cobol">*> Group data items do not have a picture clause.
01 group-item.
03 sub-data PIC X(10).
03 more-sub-data PIC X(10).</langsyntaxhighlight>
 
===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>.
<langsyntaxhighlight lang="cobol">DATA DIVISION.
WORKING-STORAGE SECTION.
01 initialized-data PIC X(15) VALUE "Hello, World!".
Line 662 ⟶ 1,180:
PROCEDURE DIVISION.
DISPLAY initialized-data *> Shows 'Hello, World!'
DISPLAY other-data *> Will probably show 15 spaces.</langsyntaxhighlight>
 
Group items can be initialized, but they are initialized with a string like so:
<langsyntaxhighlight lang="cobol">01 group-item VALUE "Hello!12345".
03 a-string PIC X(6). *> Contains "Hello!"
03 a-number PIC 9(5). *> Contains '12345'.</langsyntaxhighlight>
 
===Reference Modification===
Reference modification allows a range of characters to be taken from a variable.
<langsyntaxhighlight lang="cobol">some-str (1:1) *> Gets the first character from the string
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</langsyntaxhighlight>
 
===Scope===
Line 688 ⟶ 1,206:
Special variables may be defined with '''defparameter'''.
 
<langsyntaxhighlight lang="lisp">(defparameter *x* nil "nothing")</langsyntaxhighlight>
 
Here, the variable '''*x*''' is assigned the value nil. Special variables are wrapped with asterisks (called 'earmuffs'). The third argument is a docstring.
Line 694 ⟶ 1,212:
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.
 
<langsyntaxhighlight lang="lisp">(defvar *x* 42 "The answer.")</langsyntaxhighlight>
 
It does, however, overwrite the docstring, which you can verify:
 
<langsyntaxhighlight lang="lisp">(documentation '*x* 'variable)</langsyntaxhighlight>
 
'''defconstdefconstant''' works in the same way, but binds a constant. Constants are wrapped with '+' signs rather than earmuffs.
 
Common Lisp is case-insensitive, so saying <code>(equal +MoBy-DicK+ +moby-dick+)</code> will return '''t''' no matter the combination of upper and lower-case letters used in the symbol names. Symbols are hyphenated and lower-case.
 
For non-speciallocal varibles, we use let:
 
<langsyntaxhighlight lang="lisp">(let ((jenny (list 8 6 7 5 3 0 9))
hobo-joe)
(apply #'+ jenny))</langsyntaxhighlight>
 
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 716 ⟶ 1,234:
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.
 
<langsyntaxhighlight lang="lisp">(progn
(let ((*x* 43))
(print *x*)
(print *x*))</langsyntaxhighlight>
 
If *x* has previously been bound to the value 42, then this example will output 43, then 42.
Line 725 ⟶ 1,243:
===Mutation===
 
We use '''setf''' to modify the value of onea or more variablessymbol.
 
<syntaxhighlight lang ="lisp">(setf *x* 625)</langsyntaxhighlight>
 
We can also modify multiple symbols sequentially:
 
<syntaxhighlight lang="lisp">(setf *x* 42 *y* (1+ *x*))
=>43</syntaxhighlight>
 
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:
 
<syntaxhighlight lang="lisp">(setf *x* 625)
(psetf *x* 42 *y* (1+ *x*)
=>NIL</syntaxhighlight>
 
The return value is NIL, but the resulting value of '''*y*''' is 626 instead of 43.
 
===Types===
Common Lisp is dynamically typed, so we don't have to explicitly tell it what type of value a symbol holds. ButWe wenonetheless canhave ifthe weoption wantof being explicit about which types our functions use through '''ftype''' declarations, which tell the compiler what to expect:
 
<langsyntaxhighlight lang="lisp">(declaim (ftype (function (fixnum) fixnum) frobnicate))
(defun frobnicate (x)
(+ x 42))</syntaxhighlight>
 
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.
 
You can give the compiler the same information using in-function type declarations and the '''the''' operator:
 
<syntaxhighlight lang="lisp">(defun frobnicate (x)
(declare (type fixnum x))
(the fixnum (+ x 128)))</langsyntaxhighlight>
 
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.
A fixnum is like an unsigned integer in C. The size of a fixnum can vary by architecture, but because the Lisp virtual machine requires 2 bits for its own purposes, a fixnum can only represent 2^62 different values on a 64-bit platform.
 
=={{header|D}}==
The keyword '''the''' tells the compiler the type returned by an expression; frobnicate returns a fixnum.
<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}}==
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.
<syntaxhighlight lang="dbl">;
; Variables examples for DBL version 4 by Dario B.
;
 
.DEFINE NR,10 ;const
Whereas '''declare''' describes a function, '''declaim''' is used to inform the compiler about the program globally. The usage above gives type information about one or more functions. The '''fixnum''' in parentheses tells the compiler that the function is of one argument, being is a fixnum, and that the function returns a fixnum. We can provide any number of function names.
.DEFINE AP,"PIPPO" ;const
 
 
RECORD CUSTOM
COD, D5
NAME, A80
ZIP, D6
CITY, A80
;-----------------------
 
RECORD
 
ALPHA, A5 ;alphanumeric
NUMBR, D5 ;number
DECML, F5.2 ;float
NUMVE, 10D5 ;array of number
NUMAR, [10,2]D5 ;array of number
ALPV1, 10A8 ;array of alphanumeric
ALPV2, [NR]A8 ;array of alphanumeric
ALPA1, [10,2]A8 ;array of alphanumeric
 
NUMV, 3D3,100,200,300
ALPV, 2A3,'ABC','FGH','KLM'
MSX, A9,"VARIABLES"
MSG, A*,'Esempio di variabile autodimensionante'
 
PROC
;-----------------------------------------------------------------------
 
CLEAR ALPHA,NUMBR,DEML,NUMVE(1:10*5),NUMAR(1:10*2*5),ALPV1(1:10*8)
CLEAR ALPV2(1:10*8),ALPA1(1:10*2*8)
ALPHA="PIPPO"
NUMBR=10
DECML=20.55
 
CLEAR CUSTOM
COD=1050
NAME='Dario Benenati'
ZIP=27100
CITY="PAVIA"
 
NUMVE(1:10*5)=
NUMVE(1)=1
SET NUMVE(2),NUMVE(3),NUMVE(4)=2
NUMAR(1:10*2*5)=
NUMAR[1,1]=11
NUMAR[1,2]=12
NUMAR[2,1]=21
NUMAR[2,2]=22
 
ALPV1(1:10*8)=
ALPV1(1)="PIPPO"
APLV1(2)="PLUTO"
APLV1(2)="ABCDEFGHIJKLMNOP" ;ALPV(3)='IJKLMNOP'
 
ALPV2(1:10*8)=" "
ALPV2[1]="PIPPO"
ALPV2(2)="PLUTO"
ALPV2[3](3:2)="FO"
ALPV2[4](3,4)="FO"
 
SET ALPA1[1,1],ALPA1[1,2]="PLUTO"
ALPA1[2,1](3:2)="FO"
ALPA1[2,1](3,4)="FO"
;.....................
</syntaxhighlight>
 
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">var
<lang Delphi>var
i: Integer;
s: string;
Line 759 ⟶ 1,373:
o.Free;
end;
end;</langsyntaxhighlight>
 
=={{header|DDM}}==
Types, procs (functions) and variables in DM are built with a very "tree" structure. Because of this, there are lots of ways to define variables. Fundamentally however, the "var" keyword is always used.
<lang D>
 
float bite = 36.321; ///_Defines a floating-point number (float), "bite", with a value of 36.321
Declaring variables:
float[3] bites; ///_Defines a static array of 3 floats
<syntaxhighlight lang="dm">// Both of the following declarations can be seen as a tree,
float[] more_bites; ///_Defines a dynamic array of floats
// var -> <varname>
</lang>
var/x
var y
 
// They can also be defined like this.
// This is once again a tree structure, but this time the "var" only appears once, and the x and y are children.
var
x
y
// 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:
 
<syntaxhighlight lang="dm">// Here, "/obj" is the type, a /obj being a simple game object.
var/obj/x
// It can also be defined like this, because of the tree structure:
var
obj
x
// Or this
var/obj
x
 
// ...
// 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}}==
===Declaration===
Declaration of variables is required by the caller with the original source of the variable. If a callee hears of a variable after a declaration, it can ask around or ask the caller for the declaration; ignore the variable and any instructions associated with it; or try to determine the context and/or the callers intentions. I suppose this depends upon the mood of the callee.
 
<b>syntax:</b>
 
Use <code>add_var</code> verb-object (short for 'add variable') or the <code>dim</code> action (short for 'dimension of'):
 
<code>add_var(<i>variablename</i>);</code> or <code>dim(<i>variablename</i>);</code>
 
...multiple variables can de declared in a comma separated list.
<!-- <code>add_var(<i>variablename1</i>, <i>variablename2</i>, <i>variablename3</i>, <i>...</i>);</code> or <code>dim(<i>variablename1</i>, <i>variablename2</i>, <i>variablename3</i>, <i>...</i>);</code> -->
 
With no datatype specified, the variables are of variant type (as in basic'esque languages). Datatypes are specified using the <code>_datatype_</code> posit (can be shortened to <code>_dt</code>):
 
<code>add_var(<i>variablename</i>)_datatype(<i>datatype</i>);</code> or <code>dim(<i>variablename</i>)_dt(<i>datatype</i>);</code>
<!-- <code>add_var(<i>variablename</i>)_dt(<i>datatype</i>);</code> or <code>dim(<i>variablename</i>)_datatype(<i>datatype</i>);</code> -->
 
...or using the <code>{}</code> braces:
 
<code>add_var({<i>datatype</i>}, <i>variablename</i>);</code> or <code>dim({<i>datatype</i>}, <i>variablename</i>);</code>
<!-- <code>add_var({<i>datatype</i>}, <i>variablename1</i>, <i>variablename2</i>, <i>variablename3</i>, ...);</code> or <code>dim({<i>datatype</i>}, <i>variablename1</i>, <i>variablename2</i>, <i>variablename3</i>, <i>...</i>);</code>
<code>add_var({<i>datatype</i>}, <i>variablename1</i>, {<i>datatype</i>}, <i>variablename2</i>, {<i>datatype</i>}, <i>variablename3</i>, <i>...</i>);</code> or <code>dim({<i>datatype</i>}, <i>variablename1</i>, {<i>datatype</i>}, <i>variablename2</i>, {<i>datatype</i>}, <i>variablename3</i>, ...);</code> -->
 
<b>examples:</b>
 
<syntaxhighlight lang="diego">add_var(v1);
dim(v1);
add_var(v1, v2, v3, v4);
dim(v1, v2, v3, v4);
add_var(isRaining)_datatype(boolean);
dim(isRaining)_datatype(boolean);
add_var(greeting)_dt(string);
dim(greeting)_dt(string);
add_var({date}, birthdate);
dim({date}, birthdate);</syntaxhighlight>
 
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:
 
<syntaxhighlight lang="deigo">go_robot(alif)_waypoint(waypoint1)_addvar({bool},alifArriveWaypoint1);
go_robot(beh)_waypoint(waypoint1)_var({bool},behArriveWaypoint1);
go_robot(teh)_waypoint(waypoint1)_dim({bool},tehArriveWaypoint1);</syntaxhighlight>
 
===Initialisation===
Initialisation of variables can exist at declaration (using posit <code>_value</code> or, the shortened <code>_v</code>) or after declaration (using <code>with_var</code> then <code>_value</code>). <!--After declaration variables can be also referenced using <code>()</code> brackets. -->The first time the <code>_value</code> posit is used is the initialisation.
 
<b>syntax:</b>
 
<code>add_var<i>...</i>_value(<i>value</i>);</code>
 
<code>dim<i>...</i>_v(<i>value</i>);</code>
 
<!-- <code>(<i>variablename</i>)_value(<i>value</i>);</code> -->
 
<b>examples:</b>
 
Initialisation at declaration:
<syntaxhighlight lang="diego">add_var({integer},wholeNumber1,wholeNumber2)_value(3);
dim({double},realNumber)_v(3.0);
add_var({boolean},isRaining)_v(false);
add_var(greeting)_datatype(string)_value(Hello, this is World speaking.);</syntaxhighlight>
 
Initialisation after declaration:
<syntaxhighlight lang="diego">with_var(birthdate)_value(24-Jun-1963);
[myinteger]_value(33);</syntaxhighlight>
 
Dynamic initialisation after declaration:
<syntaxhighlight lang="diego">[myYearVar]_v(1963);
[datename]_v(24-Jun-[myYearVar]);</syntaxhighlight>
 
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>.
 
===Assignment===
Initialisation and assignment are the same, since the first assignment is the initialisation. Direct assignment of variables is achieved, as with the initialisation, using <code>_value</code> (or shortened <code>_v</code>) posit after the <code>with_var</code> verb-object or <code>[]</code> variable referencing brackets, as shown above. Assignment of a variable with other variables and operators can be achieved using the <code>_calc</code> (short for 'calculation') posit. Within the brackets of <code>_calc</code> the square brackets <code>[]</code> is be used to reference variables.
 
<b>syntax:</b>
 
<code>with_var(<i>variablename</i>)_calc(<i>expression/calculation</i>);</code>
 
<code>[<i>variablename</i>]_calc(<i>expression/calculation</i>);</code>
 
<b>examples:</b>
 
<syntaxhighlight lang="diego">with_var(d)_calc([b]^2-4*[a]*[c]);
with_var(E)_calc([m]*[c]^2);
with_var(d)_calc([b]^2-4*[a]*[c]);</syntaxhighlight>
<!--(fullname)_calc([firstname]&" "&[lastname]);
(c)_calc(++);
([c])_calc(+=[a]);
([c]+[b]);</syntaxhighlight> -->
 
Note, instead of using the <code>_calc</code> posit, all operators can be also be posits, for example:
 
<syntaxhighlight lang="diego">with_var(E)_equals(m)_multipl(c)_sq(); // E=mc²
with_var(c)_inc(); // increment by one
with_var(c)_inc(a); // same as with_var(c)_exp(+=[a]);</syntaxhighlight>
 
<!-- <syntaxhighlight lang="diego">(E)_equals(m)_multipl(c)_sq(); // E=mc²
(c)_inc(); // increment by one
(c)_inc(a); // same as [c]_exp(+=[a]);</syntaxhighlight> -->
 
===Datatypes===
Datatypes in Diego are only implied by name following the general-purpose datatypes proposed in ISO/IEC 11404. The datatype given in Diego code is presumed to be the datatype of the caller. The callee will have to presume the datatype name from the caller is the same datatype of the same name by the callee.
 
<b>syntax:</b>
 
The syntax of declaring datatypes is achieved using the <code>_datatype</code> (or shortened <code>_dt</code>) posit.
 
<code>add_var<i>...</i>_datatype(<i>datatype</i>)<i>...</i></code>
<!-- <code>add_var<i>...</i>_dt(<i>datatype</i>)<i>...</i></code> -->
 
<!-- <code>dim<i>...</i>_datatype(<i>datatype</i>)<i>...</i></code> -->
<code>dim<i>...</i>_dt(<i>datatype</i>)<i>...</i></code>
A further shortened use of the <code>{}</code> brackets can be used inside declarations<!-- and assignments-->.
 
<code>add_var({<i>datatype</i>},<i>variablename</i>)<!-- _value(<i>value</i>) -->;</code>
 
<code>dim({<i>datatype</i>},<i>variablename</i>)<!-- _value(<i>value</i>) -->;</code>
<!-- <code>add_var(<i>variablename</i>)_value({<i>datatype</i>}, <i>value</i>);</code>
<code>dim(<i>variablename</i>)_value({<i>datatype</i>}, <i>value</i>);</code> -->
 
<b>examples:</b>
 
<syntaxhighlight lang="diego">add_var(wholeNumber)_datatype(integer);
dim({double},myNumber)_v(3.0);
with_var(wholenumber)_datatype(integer);
with_var({boolean},isRaining)_value(false); // cast/converting datatype</syntaxhighlight>
<!-- ({boolean},isRaining)_value(false); // cast/converting datatype</syntaxhighlight> -->
 
However, datatypes can be implied to be variables using verb-object and posit commands, as such:
 
<b>syntax:</b>
 
<code>add_str(<i>variablename</i>)_value(<i>value</i>)</code> to declare a string datatype.
 
<code>with_bool(<i>variablename</i>)_value(<i>value</i>)</code> to reference a boolean datatype, etc.
 
<code>_float([<i>variablename</i>]=<i>value</i>)</code> to declare an integer datatype in posit state.
 
<code>_int([<i>variablename</i>]),<i>variablename</i>)</code> to declare an integer datatype in posit state, etc.
 
<b>examples:</b>
 
<syntaxhighlight lang="diego">add_str(bobName)_value(Bob);
alert_human(bob)_msg(Hi [bobName]); // Hi Bob
 
alert_human(fred)_msg(Hi [fredName])_str(fredName)_value(Freddy); // Hi Freddy</syntaxhighlight>
 
===Scope===
Variable scope is generally described a "public and interpreted" in Diego, as all variables are shared amongst thingys (humans, robots, and mobots). Every variable is 'public access', so scope is only achieved through <b>discernment</b>, <b>swarmation</b>, and <b>discrimination</b>. The keyword <code>me</code> (used as an verb-action, action, or, posit) is used to keep discernment of other thingys for use of the variable. The use of objects or criteria is used to discriminate against/for humans/robots/mobots. Then excluding objects (or using other criteria) is used to swarmate humans/robots/mobots.
 
<b>For example:</b>
 
<syntaxhighlight lang="diego">add_var(greeting)_value(Hello World)_me();</syntaxhighlight>
 
or
 
<syntaxhighlight lang="diego">with_me()_var(greeting)_value(Hello World);</syntaxhighlight>
 
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>.
 
However, the command...
 
<syntaxhighlight lang="diego">add_var(greeting)_value(Hello World);</syntaxhighlight>
 
...will share and use the variable <code>greeting</code> and its value with all thingys that received this command. This is <b>swarmation</b>.
 
However, the command...
 
<syntaxhighlight lang="diego">add_var(greeting)_value(Hello World)_for()_computer(cmp1);</syntaxhighlight>
 
...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>.
<!--
<syntaxhighlight lang="diego">with_robot(alif)_msg(Hello World);</syntaxhighlight>
 
...this command will display, via a media on <code>alif</code>'s choosing, the message "Hello World". However,...
 
<syntaxhighlight lang="diego">with_robot()_msg(Hello World);</syntaxhighlight>
 
...this command will display the message "Hello World" on every robot that receives the command. However,...
 
<syntaxhighlight lang="diego">with_computer()_msg(Hello World);</syntaxhighlight>
 
...this command will display the message "Hello World" on every computer that receives the command (but not any robots). However,...
 
<syntaxhighlight lang="diego">with_computer()_os(windows)_msg(Hello World);</syntaxhighlight>
 
...this command will display the message "Hello World" on every computer that is running Microsoft&reg; Windows&tm; that receives the command (but not any robots), and so on... -->
 
Scope also occurs within functions (<code>_funct</code> object in Diego); instructions (<code>_instruct</code> object in Diego); and, more, using the same approach with scope with variables.
 
There are also namespaces (using object <code>_namespace</code>, or, shortened, <code>_ns</code>) that contain the scope of variables, however, all variables are public inside the namespace, only differentiated between variables of the same signature (i.e. name and datatype).
 
===Referencing===
Referencing variables is achieved using the verb-object <code>with_var</code>, or implied <code>with_var</code> with the use of <code>()</code> and <code>[]</code> brackets, and combinations of.
 
When referencing variables the use of <code>()</code> brackets refers to the name of the variable. Using the <code>[]</code> brackets refers to value of the variable to be the variable name. Using the square brackets nested inside brackets, <code>([])</code>, refers the to variable name which can be manipulated. Use of <code>[[]]</code> refers to the value to the variable name to the value of the variable to be the name of the variable.
 
<b>For example:</b>
 
<syntaxhighlight lang="diego">add_var(a); // a = undefined variant
add_var({int},b); // b = undefined integer
 
with_var(a)_value(0); // a = 0 variant
with_var({int},a)_v(1); // a = 1 integer
with_var([a])_v(2); // a = 2 integer
 
with_var[a]_v(3);
// same as `with_var(3)_v(3);`
// callee will ask `with_var(3)_askdec();`
 
(a)_v(3); // a = 3 integer // same as `add_var(a)_v(3);`
([a])_v(4); // a = 4 integer // same as `add_var([a])_v(4);`
 
[a]_v(5);
// same as `with_var(3)_v(5);`
// callee will ask `with_var(3)_askdec();`
 
(a)_calc([a]+1); // a = 5
 
add_var({str},varname)_v(a);
with_var[varname]_v(6); // a = 6 integer
[varname]_inc(); // a = 7 integer // same as `with_var(a)_inc();`
 
with_var([a]+1); // a = 6 integer
with_var([a]+1)_v(7); // a = 8 integer
 
with_var([[varname]]+1); // a = 9 integer
with_var[[varname]]_inc(); // a = 10 integer
with_var([varname]+1); // varname = "a1"
 
with_var({double},a)_v(11); // a = 11.0 double
 
(varname)_v(a)_inc(2); // varname = "c" // same as `with_var(a)_v(a)_inc(2);`
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);`</syntaxhighlight>
 
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:
 
<syntaxhighlight lang="diego">alert_human(jo)_msg(Hi [])_str(joeName)_v(Joe); // Hi Joe
 
alert_human(gab)_msg(Hi [])_str()_v(Gabriella); // Hi Gabriella
 
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</syntaxhighlight>
 
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.
 
<b>For example:</b>
 
<syntaxhighlight lang="diego">alert_human(jill)_msg(Hi [jillName] Daniels)_var(jillName)_value(Jill); // Hi Jill Daniels
alert_human(jill)_msg('Hi '+[jillName]+' Daniels')_var(jillName)_value(Jill); // Hi Jill Daniels
add_var(jillFullName)_calc([jillName]+" Daniels");</syntaxhighlight>
 
=={{header|DWScript}}==
Line 772 ⟶ 1,679:
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">
<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>
</lang>
 
=={{header|Dyalect}}==
 
<syntaxhighlight lang="dyalect">//A constant declaration
let pi = 3.14
private {
//private constant, not visible outside of a module
let privateConst = 3.3
}
//Variable declaration
var x = 42
//Assignment
x = 42.42
//Dyalect is a dynamic language, so types are attached
//to values, not to the names
var foo = (x: 2, y: 4) //foo is of type Tuple
var bar = "Hello!" //bar is of type String
//Global variable
var g = 1.1
{
//local variable (not visible outside of { } brackets)
var loc = 2.2
}
func fun() {
//Local variables, not visible outside of function
var x = 1
var y = 2
}
func parent() {
//A local variable inside a parent function
var x = 1
func child() {
//A local variable inside a nested function
//It shadows a parent's variable
var x = 2
//But this is how we can reference a variable from
//a parent function
base.x
}
}</syntaxhighlight>
 
=={{header|E}}==
Line 785 ⟶ 1,741:
An identifier occurring in a pattern is a simple non-assignable variable. The <code>def</code> operator is usually used to define local variables:
 
<langsyntaxhighlight lang="e">def x := 1
x + x # returns 2</langsyntaxhighlight>
 
<!-- Using bold rather than == so as to keep the TOC sane -->
Line 793 ⟶ 1,749:
The pattern <code>var <var>x</var></code> makes <var>x</var> an assignable variable, and <code>:=</code> is the assignment operator.
 
<langsyntaxhighlight lang="e">def var x := 1
x := 2
x # returns 2</langsyntaxhighlight>
 
(As a shorthand, <code>var x := ...</code> is equivalent to <code>def var x := ...</code>.)
Line 801 ⟶ 1,757:
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:
 
<langsyntaxhighlight lang="e">def var x := 1
x += 1 # equivalent to x := x + 1, or x := x.add(1)
x # returns 2
Line 807 ⟶ 1,763:
def var list := ["x"]
list with= "y" # equivalent to list := list.with("y")
list # returns ["x", "y"]</langsyntaxhighlight>
 
'''Patterns'''
Line 813 ⟶ 1,769:
Since variable definition is part of pattern matching, a list's elements may be distributed into a set of variables:
 
<langsyntaxhighlight lang="e">def [hair, eyes, var shirt, var pants] := ["black", "brown", "plaid", "jeans"]</langsyntaxhighlight>
 
However, ''assignment'' to a list as in Perl or Python is not currently supported.
 
<langsyntaxhighlight lang="e">[shirt, pants] := ["white", "black"] # This does not do anything useful.</langsyntaxhighlight>
 
'''Scoping'''
Line 823 ⟶ 1,779:
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):
 
<langsyntaxhighlight lang="e">def list := [def x := timer.now(), x] # two copies of the current time
list[0] == x # x is still visible here; returns true</langsyntaxhighlight>
 
'''Slots'''
Line 830 ⟶ 1,786:
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:
 
<langsyntaxhighlight lang="e">def makeSum() {
var a := 0
var b := 0
Line 839 ⟶ 1,795:
x := 3
y := 4
sum() # returns 7</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="e">def getUniqueId(&counter) {
counter += 1
return counter
Line 850 ⟶ 1,806:
var idc := 0
getUniqueId(&idc) # returns 1
getUniqueId(&idc) # returns 2</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">
# it is statically typed
#
# global number variable
n = 99
print n
# global array of numbers
a[] = [ 2.1 3.14 3 ]
#
proc foo . .
# i is local, because it is first used in the function
for i = 1 to len a[]
print a[i]
.
.
foo
#
# string
domain$ = "easylang.dev"
print domain$
#
# array of strings
fruits$[] = [ "apple" "banana" "orange" ]
print fruits$[]
</syntaxhighlight>
 
=={{header|Eiffel}}==
Variables must be declared before their use with an explicit type.
<langsyntaxhighlight lang="eiffel">
class
APPLICATION
Line 878 ⟶ 1,862:
 
a: ARRAY[INTEGER]
</syntaxhighlight>
</lang>
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 888 ⟶ 1,872:
 
Assignment to variables depends on the type of variable
<langsyntaxhighlight lang="eiffel">
-- assume A and B are of the same datatype
B := A
A.some_modification_feature
</syntaxhighlight>
</lang>
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 901 ⟶ 1,885:
Global declarations:
 
<langsyntaxhighlight lang="ela">x = 42
 
sum x y = x + y</langsyntaxhighlight>
 
Local declarations:
 
<langsyntaxhighlight lang="ela">sum x y = let z = x + y in z
 
sum x y = z
where z = x + y</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 5.0:
<syntaxhighlight lang="elena">import system'collections;
 
<lang elena>#symbolpublic program =()
{
[
#var c. := nil; // declaring variable. default value is $nil
#var a := 3.; // declaring and initializing variables
#var b := "my string" length.Length;
long l := 200l; // declaring strongly typed variable
auto lst := new List<int>();
c := b + a. // assigning variable
 
].
c := b + a; // assigning variable
</lang>
}</syntaxhighlight>
 
=={{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">
<lang Erlang>
two() ->
A_variable = 1,
A_variable + 1.
</syntaxhighlight>
</lang>
 
=={{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''.
<langsyntaxhighlight lang="fsharp">let x = 5 // Int
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</langsyntaxhighlight>
 
Types are normally inferred from the values they are initialised with. However, types can be explicitly specified using ''type annotations''.
<langsyntaxhighlight lang="fsharp">let intEqual (x : int) (y : int) = x = y
let genericEqual x y : 'a = x = y</langsyntaxhighlight>
 
Mutable variables are set using the <code><-</code> operator.
<syntaxhighlight lang ="fsharp">sum <- sum + 1</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="factor">SYMBOL: foo
 
: use-foo ( -- )
Line 959 ⟶ 1,946:
a b + number>string print ;
 
: local-example ( -- str ) [let "a" :> b "c" :> a a " " b 3append ] ;</langsyntaxhighlight>
 
=={{header|Falcon}}==
<syntaxhighlight lang="falcon">
/* partially created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
 
/* global and local scrope
from the Falcon survival
guide book */
// global scope
sqr = 1.41
 
function square( x )
// local scope
sqr = x * x
return sqr
end
 
 
number = square( 8 ) * sqr
 
 
a = [1, 2, 3] // array
b = 1 // variable declaration
e = 1.0 // float
f = "string" // string
 
/* 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").
<langsyntaxhighlight lang="forth">: hypot ( a b -- a^2 + b^2 )
LOCALS| b a | \ note: reverse order from the conventional stack comment
b b * a a * + ;</langsyntaxhighlight>
 
{{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.
<langsyntaxhighlight lang="forth">: hypot { a b -- a^2 + b^2 } \ text between "--" and "}" remains commentary
a a * b b * + ;</langsyntaxhighlight>
 
Modern systems may also allow different local data types than just integer cells.
<langsyntaxhighlight lang="forth">: length { F: a F: b F: c -- len } \ floating point locals
a a F* b b F* F+ c c F* F+ FSQRT ;</langsyntaxhighlight>
 
=== 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>
</lang>
Test at the Forth Console
<pre>
Line 993 ⟶ 2,010:
=={{header|Fortran}}==
 
<langsyntaxhighlight lang="fortran"> program test
implicit none
 
Line 1,021 ⟶ 2,038:
 
end program test
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
 
<br>'''Variable declaration'''<br>
<syntaxhighlight lang="freebasic">Dim [Shared] As DataType <i>vble1</i> [, <i>vble2</i>, ...]</syntaxhighlight>
or
<syntaxhighlight lang="freebasic">Dim [Shared] <i>vble1</i> As DataType [, <i>vble2</i> As DataType, ...]</syntaxhighlight>
example:
<syntaxhighlight lang="freebasic">Dim As Integer n1, n2
Dim x As Double
Dim isRaining As Boolean
Dim As String greeting</syntaxhighlight>
 
<br>'''Initialization'''<br>
<syntaxhighlight lang="freebasic">Dim variable As datatype = value
Dim var1,var2,... As datatype</syntaxhighlight>
example:
<syntaxhighlight lang="freebasic">Dim wholeNumber1,wholeNumber2 as Integer = 3
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}}</syntaxhighlight>
 
<br>'''Assignment'''<br>
<syntaxhighlight lang="freebasic">variable = expression</syntaxhighlight>
<syntaxhighlight lang="freebasic"> v = a or v => a
d = b^2 - 4*a*c
s3 = s1 & mid(s2,3,2)</syntaxhighlight>
<syntaxhighlight lang="freebasic">variable <operator>= expression2</syntaxhighlight>
<syntaxhighlight lang="freebasic"> c += a
c -= a
c *= a
c /= a
c \= a
c ^= a
c Mod= a
c Shl= n
c Shr= n
c &amp;= a
c And= n
c Eqv= n
c Imp= n
c Or= n
c Xor= n </syntaxhighlight>
 
<br>'''Standard data types and limits.'''<br>
<br>''Numeric Types''<br>
<table border>
<tr bgcolor="#C0C0C0">
<th>Type<th>Size (bits)<th>Format<th>Minimum Value<th>Maximum Value
<tr><td>Byte <td> 8<td>signed integer<td>-128<td>+127
<tr><td>Ubyte <td> 8<td>unsigned integer<td>0<td>+255
<tr><td>Short <td> 16<td>signed integer<td>-32768<td>+32767
<tr><td>Ushort <td> 16<td>unsigned integer<td>0<td>65535
<tr><td>Long <td> 32<td>signed integer<td>-2147483648<td>+2147483647
<tr><td>Ulong <td> 32<td>unsigned integer<td>0<td>+4294967295
<tr><td>Integer <td>32/64<td>signed integer<td>32bit: -2147483648,<br>64bit: -9223372036854775808<td> 32bit: +2147483647,<br>64bit: +9223372036854775807
<tr><td>Uinteger <td>32/64<td>unsigned integer<td>0<td> 32bit: +4294967295,<br>64bit: +18446744073709551615
<tr><td>Longint <td> 64<td>signed integer<td>-9223372036854775808<td>+9223372036854775807
<tr><td>Ulongint <td> 64<td>unsigned integer<td>0<td>+18446744073709551615
<tr><td>Single <td> 32<td>floating point<td>+/-1.401 298 E-45<td> +/-3.402 823 E+38
<tr><td>Double <td> 64<td>floating point<td>+/-4.940 656 458 412 465 E-324<td> +/-1.797 693 134 862 316 E+308
<tr><td>enums <td>32/64 <td>signed integer<td>32bit: -2147483648,<br>64bit: -9223372036854775808<td>32bit: +2147483647,<br>64bit: +9223372036854775807
</table>
 
<br>''String Types''<br>
<table border>
<tr bgcolor="#C0C0C0">
<th>Type<th>Character<br>Size (bytes)<th>Minimum Size<br>(in characters)<th>Maximum Size<br>(in characters)
<tr><td>String <td> 1 <td> 0<td>32bit: +2147483647,<br>64bit: +9223372036854775807
<tr><td>Zstring <td> 1 <td> 0<td>32bit: +2147483647,<br>64bit: +9223372036854775807
<tr><td>Wstring <td> <td> 0<td>32bit: +2147483647,<br>64bit: +9223372036854775807
</table>
 
<br>'''Scope'''<br>
By default the scope of a variable is local to the <code> sub</code>, <code> function</code> or <code> module</code>. Attribute Shared can modify these scopes.
 
<tt> Shared </tt> makes module-level variables visible inside Subs and Functions.
If <tt> Shared </tt> is not used on a module-level variable's declaration, the variable is only visible to the module-level code in that file.
<br>'''Common'''<br>
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.
<syntaxhighlight lang="freebasic">Common [Shared] <i>symbolname</i>[()] [AS DataType] [, ...]</syntaxhighlight>
<br>'''Var'''<br>
Declares a variable whose type is implied from the initializer expression.
<syntaxhighlight lang="freebasic">Var [Shared] variable = expression
Var variable As datatype
Var var1,var2,... As datatype</syntaxhighlight>
example:
<syntaxhighlight lang="freebasic">Var s2 = "hello" '' var-len string
Var ii = 6728 '' implicit integer
Var id = 6728.0 '' implicit double</syntaxhighlight>
 
=={{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}}==
 
<langsyntaxhighlight lang="gap"># At top level, global variables are declared when they are assigned, so one only writes
global_var := 1;
 
Line 1,048 ⟶ 2,180:
IsBound(u[3]);
# false
Unbind(u[4]);</langsyntaxhighlight>
 
=={{header|GlovePIE}}==
<syntaxhighlight lang="glovepie">if var.end=0 then // Without the code being in this if statement, the code would keep executing until it were to stop.
var.end=1
// These variables, respectively, refer to an integer, a boolean, and a string.
var.variable1=3
var.variable2=True
var.variable3="Hi!"
// var.example1 now refers to a string object instead.
var.variable1="Bye!"
endif</syntaxhighlight>
 
=={{header|Go}}==
Line 1,054 ⟶ 2,197:
 
While Go is statically typed, it provides a “short variable declaration” with no type explicitly stated, as in,
<langsyntaxhighlight lang="go">x := 3</langsyntaxhighlight>
This is the equivalent of,
<langsyntaxhighlight lang="go">var x int // declaration
x = 3 // assignment</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="go">y := x+1 // y is int, assuming declaration above
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</langsyntaxhighlight>
'''Nothing goes uninitialized'''
 
Variables declared without initializer expressions are initialized to the zero value for the type.
<langsyntaxhighlight lang="go">var x, y int // two variables, initialized to zero.
var p *int // initialized to nil</langsyntaxhighlight>
'''Opposite C'''
 
Line 1,075 ⟶ 2,218:
 
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.
<langsyntaxhighlight lang="go">var (
x, y int
s string
)</langsyntaxhighlight>
'''Multiple assignment'''
 
Multiple values can be assigned in a single assignment statement, with many uses.
<langsyntaxhighlight lang="go">x, y = y, x // swap x and y
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]</langsyntaxhighlight>
'''Other kinds of local variables'''
 
Parameters and named return values of functions, methods, and function literals also represent assignable local variables, as in,
<langsyntaxhighlight lang="go">func increase (x int) (more int) {
x++
more = x+x
return
}</langsyntaxhighlight>
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 1,103 ⟶ 2,246:
 
Short declarations can involve multiple assignment, as in
<langsyntaxhighlight lang="go">x, y := 3, 4</langsyntaxhighlight>
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 1,112 ⟶ 2,255:
You can define a variable at the top (module) level or in a <code>where</code>, <code>let</code>, or <code>do</code> construct.
 
<langsyntaxhighlight lang="haskell">foobar = 15
 
f x = x + foobar
Line 1,122 ⟶ 2,265:
f x = do
let foobar = 15
return $ x + foobar</langsyntaxhighlight>
 
One particular feature of <code>do</code> notation looks like assignment, but actually, it's just syntactic sugar for the <code>&gt;&gt;=</code> operator and a unary lambda.
 
<langsyntaxhighlight lang="haskell">main = do
s <- getLine
print (s, s)
Line 1,132 ⟶ 2,275:
-- The above is equivalent to:
 
main = getLine >>= \s -> print (s, s)</langsyntaxhighlight>
 
''Pattern matching'' allows for multiple definitions of the same variable, in which case each call uses the first applicable definition.
 
<langsyntaxhighlight lang="haskell">funkshun True x = x + 1
funkshun False x = x - 1
 
foobar = funkshun True 5 + funkshun False 5 -- 6 + 4</langsyntaxhighlight>
 
<code>case</code> expressions let you do pattern-matching on an arbitrary expression, and hence provide yet another way to define a variable.
 
<langsyntaxhighlight lang="haskell">funkshun m = case foo m of
[a, b] -> a - b
a : b : c : rest -> a + b - c + sum rest
a -> sum a</langsyntaxhighlight>
 
''Guards'' are as a kind of syntactic sugar for if-else ladders.
 
<langsyntaxhighlight lang="haskell">signum x | x > 0 = 1
| x < 0 = -1
| otherwise = 0</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="haskell">dotProduct :: [Int] -> [Int] -> Int
dotProduct ns ms = sum $ zipWith (+) ns ms
-- Without the type signature, dotProduct would
Line 1,165 ⟶ 2,308:
-- Without the type signature, the monomorphism
-- restriction would cause foobar to have a less
-- general type.</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight HicEstlang="hicest">! Strings and arrays must be declared.
! Everything else is 8-byte float, READ/WRITE converts
CHARACTER str="abcdef", str2*345, str3*1E6/"xyz"/
Line 1,202 ⟶ 2,345:
USE Arguments_or_USE : t ! use local object
func = t
END</langsyntaxhighlight>
 
=={{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="holyc">U8 i;</syntaxhighlight>
 
Some common types are: <i>I8, I64, U8, U64, F64</i>.
 
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>
<syntaxhighlight lang="holyc">U8 b1 = 8;
U8 b2 = b1 * 10;</syntaxhighlight>
 
Multiple variables may be defined in a single statement as follows:
<syntaxhighlight lang="holyc">U8 uint1, uint2, uint3;</syntaxhighlight>
 
To initialized a string:
<syntaxhighlight lang="holyc">U8 *str = "The HolyC Language";</syntaxhighlight>
 
== Icon and Unicon ==
Line 1,208 ⟶ 2,368:
 
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.
<langsyntaxhighlight Iconlang="icon">global gvar # a global
 
procedure main(arglist) # arglist is a parameter of main
Line 1,220 ⟶ 2,380:
 
# ... rest of program
end</langsyntaxhighlight>
 
==={{header|Icon}}===
Line 1,228 ⟶ 2,388:
=={{header|J}}==
 
<syntaxhighlight lang="j">
<lang j>val=. 0</lang>
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">
<lang j>fun =: 3 :0
fun =: 3 :0
val1 =: 0
val1 =. 2
Line 1,243 ⟶ 2,406:
0
val2
|value error</lang>
</syntaxhighlight>
 
Note that the language forbids assigning a "global" value in a context where the name has a local definition.
 
<syntaxhighlight lang="j">
<lang j>fun1 =: 3 :0
fun1 =: 3 :0
val3=. 0
val3=: 0
)
fun1''
|domain error</lang>
</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">
<lang j>fun2 =: 3 :0
fun2 =: 3 :0
val4=. 0
3 :'val4=:y' y
)
fun2 ''</lang>
</syntaxhighlight>
 
Variables are referred to by name, and exist in locales (which may be used as classes, closures or other stateful references).
Line 1,270 ⟶ 2,438:
=={{header|Java}}==
Variables in Java are declared before their use with explicit types:
<langsyntaxhighlight lang="java">int a;
double b;
AClassNameHere c;</langsyntaxhighlight>
Several variables of the same type can be declared together:
<syntaxhighlight lang ="java">int a, b, c;</langsyntaxhighlight>
Variables can be assigned values on declaration or afterward:
<langsyntaxhighlight lang="java">int a = 5;
double b;
int c = 5, d = 6, e, f;
String x = "test";
String y = x;
b = 3.14;</langsyntaxhighlight>
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):
<langsyntaxhighlight lang="java">final String x = "blah";
final String y;
final double[] nums = new double[15];
Line 1,294 ⟶ 2,462:
final Date now = new java.util.Date();
now.setTime(1234567890); //legal
now = new Date(1234567890); //not legal</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 1,305 ⟶ 2,473:
When resolving a variable, javascript starts at the innermost scope and searches outwards.
 
<div style='height:30em;width:full;overflow:scroll'><langsyntaxhighlight lang="javascript">// a globally-scoped variable
var a=1;
 
Line 1,371 ⟶ 2,539:
six();
alert(new Seven().a);
alert(new Seven().b);</langsyntaxhighlight></div>
 
=={{header|Joy}}==
JOY does not have variables. Variables essentially name locations in memory, where values are stored. JOY also uses memory to store values, but has no facility to name these locations. The memory that JOY uses is commonly referred to as "the stack".
Line 1,378 ⟶ 2,547:
 
The JOY stack can be initialized:
<syntaxhighlight lang ="joy">[] unstack</langsyntaxhighlight>
 
'''Assignment'''
 
Values can be pushed on the stack:
<syntaxhighlight lang ="joy">42</langsyntaxhighlight>
pushes the value 42 of type integer on top of the stack.
 
Line 1,389 ⟶ 2,558:
 
Calling the stack by name pushes a copy of the stack on the stack. To continue the previous example:
<syntaxhighlight lang ="joy">stack</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="jq">jq -n '1 as $x | (2 as $x | $x) | $x'</langsyntaxhighlight>
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 1,399 ⟶ 2,569:
 
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 ="jq">EXPRESSION as $NAME</langsyntaxhighlight>
This establishes $NAME as a reference to the value of EXPRESSION. There is no special syntax to constrain the type of a variable.
 
Line 1,405 ⟶ 2,575:
 
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:
<langsyntaxhighlight lang="jq">def test: $x;
test</langsyntaxhighlight>
The following invocation:
<langsyntaxhighlight lang="sh">jq --arg x 123 -n -f test.jq</langsyntaxhighlight>
will result in the string "123" being output.
 
=={{header|Liberty BASIC}}==
<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).
'There is no practical limit to the length of a variable name... up to ~2M characters.
'The variable names are case sensitive.
 
'assignments: -numeric variables. LB assumes integers unless assigned or calculated otherwise.
'Because of its Smalltalk heritage, LB integers are of arbitrarily long precision.
'They lose this if a calculation yields a non-integer, switching to floating point.
i = 1
r = 3.14
 
'assignments -string variables. Any string-length, from zero to ~2M.
t$ ="21:12:45"
flag$ ="TRUE"
 
'assignments -1D or 2D arrays
'A default array size of 10 is available. Larger arrays need pre-'DIM'ming.
height( 3) =1.87
dim height( 50)
height( 23) =123.5
potential( 3, 5) =4.5
name$( 4) ="John"
 
'There are no Boolean /bit variables as such.
 
'Arrays in a main program are global.
'However variables used in the main program code are not visible inside functions and subroutines.
'They can be declared 'global' if such visibility is desired.
'Functions can receive variables by name or by reference.
</lang>
=={{header|Julia}}==
Certain constructs in the language introduce scope blocks, which are regions of code that are eligible to be the scope of some set of variables. The scope of a variable cannot be an arbitrary set of source lines, but will always line up with one of these blocks. The constructs introducing such blocks are:
Line 1,454 ⟶ 2,591:
let blocks
type blocks.
<langsyntaxhighlight lang="julia">#declaration/assignment, declaration is optional
x::Int32 = 1
#datatypes are inferred dynamically, but can also be set thru convert functions and datatype literals
Line 1,468 ⟶ 2,605:
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</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="julia">const e = 2.71828182845904523536
const pi = 3.14159265358979323846</langsyntaxhighlight>
 
=={{header|Kotlin}}==
Local variables in Kotlin (i.e. variables created within a function, constructor or a property getter/setter) must be individually declared and initialized before they are used. They then remain in scope until the end of the block in which they are declared though their lifetime may be extended if they are 'captured' by a closure of some kind.
 
A variable's type can either be inferred from the type of the initialization expression or can be declared explicitly.
There are essentially two types of variables: read-only (declared with 'val') and mutable (declared with 'var').
 
Variables declared at top-level or class/object scope are technically properties rather than variables and only have hidden backing fields where necessary. However, like local variables, they are either read-only or mutable and (in the case of top level or object properties) can be declared to be compile-time constants using the 'const val' modifier.
 
Here are some examples of local variables:
<syntaxhighlight lang="scala">// version 1.0.6
 
fun main(args: Array<String>) {
/* read-only variables */
val i = 3 // type inferred to be Int
val d = 2.4 // type inferred to be double
val sh: Short = 2 // type specified as Short
val ch = 'A' // type inferred to be Char
val bt: Byte = 1 // type specified as Byte
 
/* mutable variables */
var s = "Hey" // type inferred to be String
var l = 4L // type inferred to be Long
var b: Boolean // type specified as Boolean, not initialized immediately
var f = 4.4f // type inferred to be Float
 
b = true // now initialized
println("$i, $d, $sh, $ch, $bt, $s, $l, $b, $f")
s = "Bye" // OK as mutable
l = 5L // OK as mutable
b = false // OK as mutable
f = 5.6f // OK as mutable
 
println("$i, $d, $sh, $ch, $bt, $s, $l, $b, $f")
}</syntaxhighlight>
 
{{out}}
<pre>
3, 2.4, 2, A, 1, Hey, 4, true, 4.4
3, 2.4, 2, A, 1, Bye, 5, false, 5.6
</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
1) working in a global scope
 
{def A 3}
-> A // A is in the global scope
{def B 4}
-> B // B is in the global scopel
{def MUL {lambda {:x :y} {* :x :y}}}
-> MUL // MUL is a global function
{MUL {A} {B}} // using global variables
-> 12
 
2) working in a local scope
 
{let // open local scope
{ // begin defining and assigning local variables
{:a 3} // :a is local
{:b 4} // :b is local
{:mul {lambda {:x :y} {* :x :y}}} // :mul is a local function
} // end defining and assigning local variables
{:mul :a :b} // computing with local variables
} // closing local scope
-> 12
</syntaxhighlight>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">// declare thread variable, default type null
var(x)
$x->type // null
Line 1,516 ⟶ 2,719:
'\r'
#copy // unmodified as it used ascopydeep
//array(RADISH, CARROT, CUCUMBER, OLIVE)</langsyntaxhighlight>
 
=={{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).
'There is no practical limit to the length of a variable name... up to ~2M characters.
'The variable names are case sensitive.
 
'assignments: -numeric variables. LB assumes integers unless assigned or calculated otherwise.
'Because of its Smalltalk heritage, LB integers are of arbitrarily long precision.
'They lose this if a calculation yields a non-integer, switching to floating point.
i = 1
r = 3.14
 
'assignments -string variables. Any string-length, from zero to ~2M.
t$ ="21:12:45"
flag$ ="TRUE"
 
'assignments -1D or 2D arrays
'A default array size of 10 is available. Larger arrays need pre-'DIM'ming.
height( 3) =1.87
dim height( 50)
height( 23) =123.5
potential( 3, 5) =4.5
name$( 4) ="John"
 
'There are no Boolean /bit variables as such.
 
'Arrays in a main program are global.
'However variables used in the main program code are not visible inside functions and subroutines.
'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:
<syntaxhighlight lang="lingo">x = 23
y = "Hello world!"
z = TRUE -- same effect as z = 1</syntaxhighlight>
 
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":
<syntaxhighlight lang="lingo">on foo
put x
end</syntaxhighlight>
 
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:
<syntaxhighlight lang="lingo">put value("x")
-- <Void> -- means: undefined</syntaxhighlight>
 
But variable declarations/assignments can also explicitely assign the constant VOID. The following script compiles successfully, but value("x") would still return <Void>:
<syntaxhighlight lang="lingo">on foo
x = VOID
put x
end</syntaxhighlight>
 
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:
<syntaxhighlight lang="lingo">global x
on foo
put x
end</syntaxhighlight>
<syntaxhighlight lang="lingo">on foo
global x
put x
end</syntaxhighlight>
 
Global variables can also be declared/created at runtime, by adding them as property to the special _global object:
<syntaxhighlight lang="lingo">_global.x = 23</syntaxhighlight>
 
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="lingo">put _global.x</syntaxhighlight>
 
=={{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}}
<langsyntaxhighlight lang="logo">make "g1 0
name 2 "g2 ; same as make with parameters reversed
global "g3 ; no initial value
Line 1,540 ⟶ 2,813:
print :g4 ; 4
print :L1 ; L1 has no value
print name? "L1 ; false, L1 is not bound in the current scope</langsyntaxhighlight>
 
=={{header|LotusScript}}==
 
<langsyntaxhighlight Lotusscriptlang="lotusscript">Sub Click()
'a few declarations as example
Dim s as New NotesSession ' declaring a New NotesSession actually returns the current, active NotesSession
Line 1,556 ⟶ 2,829:
 
End Sub
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
In lua, variables are dynamically typecast, and do not need declaration prior to use.
 
<langsyntaxhighlight lang="lua">a = 1 -- Here we declare a numeric variable
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 </langsyntaxhighlight>
 
The lua programming language supports multiple assignments from within a single statement:
 
<langsyntaxhighlight lang="lua">A, B, C, D, E = 2, 4, 6, 8, "It's never too late"</langsyntaxhighlight>
 
=={{header|MathematicaM2000 Interpreter}}==
Each module has own local variables and can create global variables. A local variable shadow any global with same name. A new global with same name shadow a global variable (but its wrong to create a local first with same name, we see local always). We can change global variables, but to assign to a global variable we need to use <=. Arrays defined with DIM and global arrays not use <= for assign values to items.
 
Variables can exist in Groups as public or private. Also variables can be closures in lambda functions.
 
We can use '''Local''' to make local variables, '''Let''' to make variables, '''Def''' to make once variables (second time using Def for same variable we get error). We can use '''Input''' and '''Read''' to make new variables too. We can assign a value to new name, to make a variable.
 
 
 
<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
\\ @ for Decimal
\\ # for Currency
\\ ~ for Single
\\ & for Long (32bit)
\\ % for Integer (16bit)
\\ Double and Boolean have no symboles
Module TopA {
Module Alfa {
Print A=10000, Type$(A)="Double"
\\ A is local, we use =
A=10@
Print A=10, Type$(A)
\\ Or we can state the type before
Def Currency K, Z=500, M
K=1000
\\ Currency Currency Currency
Print Type$(K), Type$(Z), Type$(M)
Def Double K1, K2 as Integer=10, K3=1
\\ double integer double
Print Type$(K1), Type$(K2), Type$(K3)
Mb=1=1
\\ We get a boolean
Print Type$(Mb)
Def boolean Mb1=True
Print Type$(Mb1)
\\ True and False are Double -1 and 0 not Boolean
Mb3=True
Print Type$(Mb3)="Double"
\\ For strings we have to use $ (like in old Basic)
A$="This is a String"
Global G1 as boolean = True
\\ To change a global variable we have to use <=
G1<=1=0
\\ If we do this: G1=1=0 we make a local variable, and shadow global
\\ In a For Object {} we can make temporary variables
For This {
Local G1=122.1212
Print G1, Type$(G1)="Double"
}
Print G1, Type$(G1)="Boolean"
}
\\ shadow A for this module only
A=100
\\ Now we call Alfa
Alfa
Print (A=100)=True
}
Global A=10000
TopA
Print A=10000
Module CheckStatic {
\\ clear static variables and variables (for this module)
Clear
Module K {
\\ if no A exist created with value 100@
\\ Static variables can't be referenced
Static A=100@
Print A, Type$(A)="Decimal"
A++
}
For i=1 to 10 : K : Next i
Print A=10000
}
CheckStatic
Print A=10000
 
\\ reference and use of stack of values
C=100&
Module ChangeC {
\\ we leave arguments in stack of values
Module HereChangeC (&f) {
\\ interpreter execute a Read &f
f++
}
\\ now we call HereChangeC passing current stack of values
HereChangeC
}
\\ Calling a module done without checking for what parameters a module take
ChangeC &C
Print C, Type$(C)="Long"
K=10010001001@
ChangeC &K
Print K, Type$(K)="Decimal"
Module TypeRef (&x as Double) {
Print x
x++
}
D=100
TypeRef &D
Try ok {
TypeRef &K
}
If Error or Not Ok then Print Error$ ' we get wrong data type
</syntaxhighlight>
 
=={{header|Maple}}==
Variables are dynamic in Maple, so they do not need to be defined before they are used.
 
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.
<syntaxhighlight lang="maple">a := 1:
print ("a is "||a);
"a is 1"</syntaxhighlight>
 
 
Variables in a procedure should be declared with the "local" or "global" keyword.
 
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.
<syntaxhighlight lang="maple">b;
f := proc()
local b := 3;
print("b is "||b);
end proc:
f();
print("b is "||b);
b
"b is 3"
"b is b"</syntaxhighlight>
 
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.
<syntaxhighlight lang="maple">f := proc()
global c;
c := 3;
print("a is "||a);
print("c is "||c);
end proc:
f();
print("c is "||c);
"a is 1"
"c is 3"
"c is 3"</syntaxhighlight>
 
 
Variables can be reassigned.
<syntaxhighlight lang="maple">print ("a is "||a);
a := 4:
print ("a is "||a);
"a is 1"
"a is 4"</syntaxhighlight>
 
 
Variables can be reassigned as different datatypes.
<syntaxhighlight lang="maple">print ("a is "||a);
type(a, integer);
a := "Hello World":
print ("a is "||a);
type(a, integer);
type(a, string);
"a is 4"
true
"a is Hello World"
false
true</syntaxhighlight>
 
 
Variable names may contain spaces and other characters when you enclose them in ``.
<syntaxhighlight lang="maple">`This is a variable` := 1:
print(`This is a variable`);
1</syntaxhighlight>
 
 
To unassign a variable.
<syntaxhighlight lang="maple">print ("a is "||a);
type(a, string);
print("c is "||c);
a := 'a':
print ("a is "||a);
type(a, symbol);
unassign('c');
print("c is "||c);
"a is Hello World"
true
"c is 3"
"a is a"
true
"c is c"</syntaxhighlight>
Here, symbol is essentially another term for variable name.
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<pre>x=value assign a value to the variable x
x=y=value assign a value to both x and y
Line 1,622 ⟶ 3,087:
=={{header|MATLAB}} / {{header|Octave}}==
 
<langsyntaxhighlight Matlablang="matlab"> a = 4; % declare variable and initialize double value,
s = 'abc'; % string
i8 = int8(5); % signed byte
Line 1,632 ⟶ 3,097:
i64 = int64(5); % signed 8 byte integer
u64 = uint64(5);% unsigned 8 byte integer
f32 = float32(5); % single precissionprecision floating point number
f64 = float64(5); % double precissionprecision floating point number , float 64 is the default data type.
 
c = 4+5i; % complex number
colvec = [1;2;4]; % column vector
crowvec = [1,2,4]; % row vector
m = [1,2,3;4,5,6]; % matrix with size 2x3</langsyntaxhighlight>
 
Variables within functions have local scope, except when they are declared as global
 
<syntaxhighlight lang Matlab="matlab"> global b </langsyntaxhighlight>
 
=={{header|Mercury}}==
 
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:
 
<syntaxhighlight lang="mercury">:- func name = string.
name = Name :-
Name = Title ++ " " ++ Given,
Title = "Dr.",
Given = "Bob".</syntaxhighlight>
 
Mercury also has state variables, actually pairs of variables, usually instantiated in the head of a rule.
 
<syntaxhighlight lang="mercury">:- pred greet(string::in, io::di, io::uo) is det.
greet(Who, !IO) :-
io.write_string("Hello", !IO),
io.format(", %s!\n", [s(Who)], !IO).</syntaxhighlight>
 
In this example <code>!IO</code> is the state variable, and this code translates to
 
<syntaxhighlight lang="mercury">:- pred greet(string::in, io::di, io::uo) is det.
greet(Who, !.IO, !:IO) :-
io.write_string("Hello", !.IO, !:IO),
io.format(", %s!\n", [s(Who)], !.IO, !:IO).</syntaxhighlight>
 
which translates roughly to:
 
<syntaxhighlight lang="mercury">:- pred greet(string::in, io::di, io::uo) is det.
greet(Who, IO0, IO) :-
io.write_string("Hello", IO0, IO1),
io.format(", %s!\n", [s(Who)], IO1, IO).</syntaxhighlight>
 
<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.)
 
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:
 
<syntaxhighlight lang="mercury">:- func dr(string) = string.
dr(Name) = Titled :-
some [!SB] (
!:SB = string.builder.init,
put_char(handle, 'D', !SB),
put_char(handle, 'r', !SB),
format(handle, " %s", [s(Name)], !SB),
Titled = to_string(!.SB)
).</syntaxhighlight>
 
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.
 
<syntaxhighlight lang="mercury"> % all_under(N, L)
% 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).</syntaxhighlight>
 
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.
 
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:
 
<syntaxhighlight lang="mercury">:- type accumulator == (pred(int, int, io, io)).
:- inst accumulator == (pred(in, out, di, uo) is det).
 
:- func accumulator >> accumulator = accumulator.
:- mode in(accumulator) >> in(accumulator) = out(accumulator).
A >> B = C :-
C = (pred(!.N::in, !:N::out, !.IO::di, !:IO::uo) is det :-
A(!N, !IO),
B(!N, !IO)).
 
:- pred add(int::in, int::in, int::out, io::di, io::uo) is det.
add(N, !Acc, !IO) :-
io.format("adding %d to accumulator (current value: %d)\n",
[i(N), i(!.Acc)], !IO),
!:Acc = !.Acc + N.
 
:- pred example2(io::di, io::uo) is det.
example2(!IO) :-
F = add(5)
>> add(5)
>> add(-10),
F(0, X, !IO),
io.print_line(X, !IO).</syntaxhighlight>
 
{{out}}
<pre>adding 5 to accumulator (current value: 0)
adding 5 to accumulator (current value: 5)
adding -10 to accumulator (current value: 10)
0</pre>
 
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:
 
<syntaxhighlight lang="mercury">:- module evenodd.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module list, string.
 
:- type coin
---> heads
; tails.
 
:- inst heads for coin/0
---> heads.
:- inst tails for coin/0
---> tails.
 
main(!IO) :-
(if heads(heads, N) then
print_heads(N, !IO)
else true).
 
:- pred print_heads(coin::in(heads), io::di, io::uo) is det.
print_heads(_, !IO) :-
io.write_string("heads\n", !IO).
 
:- pred print_tails(coin::in(tails), io::di, io::uo) is det.
print_tails(_, !IO) :-
io.write_string("tails\n", !IO).
 
:- pragma foreign_export_enum("C", coin/0, [prefix("COIN_"), uppercase]).
 
:- pred heads(coin::in, coin::out(heads)) is semidet.
:- pragma foreign_proc("C",
heads(N::in, M::out(heads)),
[promise_pure, will_not_call_mercury],
"
M = N;
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.
 
=={{header|MIPS Assembly}}==
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.
 
<syntaxhighlight lang="mips">foo equ 0x100
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.</syntaxhighlight>
 
Initialization is done by setting the variable equal to a value. For variables that live entirely in a register, this is very simple:
<syntaxhighlight lang="mips">li $t0,5 ;load the register $t0 with the value 5.</syntaxhighlight>
 
For memory, this is a bit harder.
<syntaxhighlight lang="mips">.definelabel USER_RAM,0xA0000000
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</syntaxhighlight>
 
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}}==
<langsyntaxhighlight lang="modula3">MODULE Foo EXPORTS Main;
 
IMPORT IO, Fmt;
Line 1,659 ⟶ 3,277:
BEGIN
Foo();
END Foo.</langsyntaxhighlight>
 
For procedures, the formal parameters create local variables unless the actual parameter is prefixed by VAR:
<langsyntaxhighlight lang="modula3">PROCEDURE Foo(n: INTEGER) =</langsyntaxhighlight>
Here, <tt>n</tt> will be local to the procedure Foo, but if we instead wrote:
<langsyntaxhighlight lang="modula3">PROCEDURE Foo(VAR n: INTEGER) =</langsyntaxhighlight>
Then <tt>n</tt> is the global variable <tt>n</tt> (if it exists).
 
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">// variable definition and initialization/assignment
//
// variables are initialized when they are defined
a = 1
b = 2
c = null
 
// datatypes
//
// variables may contain any datatype, and this can be
// changed at any time by assigning a new value. they may
// also contain native java types
var = "a string"
var = 123
var = new(Nanoquery.Util.Random)
var = new(java.lang.Object)
 
// scope
//
// all classes, functions, and control blocks have their
// own scope
x = 5
for i in range(1, 2)
// we can reference 'x' within this loop without issue
println x
 
// we can also define variables that have this loop as their
// scope
y = 5
end
// trying to reference the variable 'y' outside of its scope would result
// in a null reference exception
println y
//%null reference exception: variable object 'y' has not been defined
// at <global>:33
 
 
// referencing
//
// as already demonstrated, variables are referenced by using their
// name
part1 = "this is "
part2 = "a test sentence"
println part1 + part2
 
// other facilities
//
// variables may be marked for garbage collection in their current
// scope using the 'delete' command
test_var = "pretend this is a really large object we want to free up"
delete test_var</syntaxhighlight>
 
=={{header|Nim}}==
<lang nim>var x: int = 3
 
1) Declaration
var y = 3 # type inferred to int
Nim variables are declared with the keyword <code>var</code> for mutable variables and <code>let</code> for immutable variables. The declaration may be done at the module level (global variables) or in procedures, iterators, methods. At module level, when the name of a variable is followed by an asterisk (<code>*</code>) the variable is considered as exported and will be visible in other modules which import the declaration module.
 
It is possible to declare several variables in the same declaration statement.
var z: int # initialized to 0
 
2) Initialization
let a = 13 # immutable variable
 
All variables are implicitly initialized to binary zero (which includes data allocated on the heap as strings and sequences). An initialization value may, of course, be specified.
 
When declaring a variable, the type must be specified, except if the variable is initialized as the type is determined from the initialization value. Immutable variables must be initialized at their declaration point.
 
If there is more than one variable initialized in the declaration statement, the expression is evaluated several times (this is important if the initialization expression contains a call to a procedure causing side-effects).
 
3) Assignment
 
Variables are assigned using the statement <code>variable = expression</code>. For structured objects, assigning causes generally a copy. There exists some mechanisms to avoid the copy, but they should be used with care.
 
4) References and pointers
 
Nim allows to declare references and pointers, for instance <code>var p: ref int</code>. Such variables are implicitly initialized to binary zero which is the value <code>nil</code>. For references, the allocation of data is done with the procedure <code>new</code> or implicitly in some cases. For pointers, there are several procedures similar to C allocation functions, for instance <code>alloc</code> or <code>alloc0</code>.
 
4) Scope
 
Global variables may be accessed from anywhere provided they are visible. To make a variable from another module visible, the module must be imported or, at least, the variable form the module must be imported. To access the field of an object, these fields must have been exported (using an asterisk as for exportation of a variable).
 
In a procedure “p”, local variables are visible from procedures declared inside “p”. However, Nim may prevent some operations on variables from an outside scope if they could result in a violation of the memory integrity.
 
5) Referencing
 
Variables may be referenced by their name or by their qualified name. The qualified name is the name preceded by the module name and a dot, for instance <code>m.x</code>.
 
Data managed via a reference or a pointer “p” may be accessed using the notation <code>p[]</code>. If the accessed data is an object containing some field “a” the short notation <code>p.a</code> may be used instead of the full notation <code>p[].a</code>.
 
6) Examples
 
<syntaxhighlight lang="nim">var x: int = 3 # Declaration with type specification and initialization.
 
var y = 3 # Declaration with type inferred to "int".
 
var z: int # Variable is initialized to 0.
 
let a = 13 # Immutable variable.
 
# Using a var block to initialize.
var
b, c: int = 10 # Two variables initialized to 10
s* = "foobar"</lang> # This one is exported.
 
type Obj = ref object
i: int
s: string
 
var obj = Obj(i: 3, s: "abc") # Initialization with an implicit allocation by "new".
echo obj.a, " ", obj.s # Equivalent to obj[].a and obj[].s.
 
proc p =
var xloc = 3
echo x # Referencing a global variable.
 
proc q =
echo xloc # Referencing a variable in the enclosing scope.</syntaxhighlight>
 
=={{header|Objeck}}==
Different ways to declare and initialize an integer.
<langsyntaxhighlight lang="objeck">
a : Int;
b : Int := 13;
c := 7;
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
Line 1,692 ⟶ 3,414:
 
The standard way to bind an identifier to a value is the '''let''' construct:
<langsyntaxhighlight lang="ocaml">let x = 28</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="ocaml">let y = ref 28</langsyntaxhighlight>
References can then be accessed and modified this way:
<langsyntaxhighlight lang="ocaml"> !y (* access *)
y := 34 (* modification *)</langsyntaxhighlight>
 
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):
<langsyntaxhighlight lang="ocaml">let sum = (* sum is bound to 181 *)
let a = 31
and b = 150 in
Line 1,713 ⟶ 3,435:
let a = 31
and b = 150 in
(a + b)</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 1,732 ⟶ 3,454:
Using -> removes the top of the stack and assign this value to the variable
 
<syntaxhighlight lang="oforth">import: date
<lang Oforth>func: testVariable
 
{
: testVariable
| a b c |
Date now ->a
a println ;</syntaxhighlight>
}</lang>
 
=={{header|ooRexx}}==
While REXX (and ooRexx) normally pass arguments ''by value''. ooRexx has a mechanism to pass compound variables ''by recerencereference''.
<syntaxhighlight lang="text">a.=4711
Say 'before sub a.3='a.3
Call sub a.
Line 1,749 ⟶ 3,471:
use Arg a.
a.3=3
Return</langsyntaxhighlight>
{{out}}
<pre>before sub a.3=4711
after sub a.3=3</pre>
 
=={{header|Ol}}==
 
Ol is a purely functional Lisp, so there are no variables in common sense in Ol. We use 'symbol' and 'linked value' instead.
 
<syntaxhighlight lang="scheme">
; Declare the symbol 'var1' and associate number 123 with it.
(define var1 123)
(print var1)
; ==> 123
 
; Reassociate number 321 with var1.
(define var1 321)
(print var1)
 
; Create function that prints value of var1 ...
(define (show)
(print var1))
; ... and eassociate number 42 with var1.
(define var1 42)
 
(print var1)
; ==> 42
; var1 prints as 42, but...
(show)
; ==> 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.
... tbd...
 
=={{header|Openscad}}==
 
<langsyntaxhighlight lang="openscad">
mynumber=5+4; // This gives a value of nine
</syntaxhighlight>
</lang>
 
=={{header|OxygenBasic}}==
<syntaxhighlight lang="text">
'WAYS OF DECLARING VARIABLES
'AND ASSIGNING VALUES
var int a,b,c,d
int a=1,b=2,c=3,d=4
dim int a=1,b=2, c=3, d=4
dim as int a=1,b=2, c=3, d=4
dim a=1,b=2, c=3, d=4 as int
print c '3
 
'CREATING ARRAY VARIABLES
int array[100]
dim int a={10,20,30,40} 'implicit array
print a[3] '30
 
'COMMONLY USED TYPES:
'byte word int sys float char string
 
'LIMITING SCOPE
dim int a=10
scope
dim int a=100
dim int b=1000
print a '100
end scope
print a 'prior a: 10
print b 'error b is out of scope
 
'REFERENCING VARIABLES
dim int*p 'p is a pointer variable
dim int a={2,4,6,8}
@p=@a[3] 'address of p is assigned address of a[3]
print @p 'the address
print p '6
print p[1] '6
print p[2] '8
</syntaxhighlight>
 
=={{header|Oz}}==
Line 1,764 ⟶ 3,556:
 
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:
<langsyntaxhighlight lang="oz">declare
Var %% new variable Var, initially free
{Show Var}
Line 1,770 ⟶ 3,562:
{Show Var}
Var = 42 %% the same value is assigned again: ok
Var = 43 %% a different value is assigned: exception</langsyntaxhighlight>
 
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 1,777 ⟶ 3,569:
 
Assignment to dataflow variables is also called unification. It is actually a symmetric operation, e.g. the following binds B to 3:
<langsyntaxhighlight lang="oz">declare
A = 3
B
in
A = B
{Show B}</langsyntaxhighlight>
 
However, variables can only be introduced at the left side of the <code>=</code> operator. So this is a syntax error:
<langsyntaxhighlight lang="oz">declare
A = 3
A = B %% Error: variable B not introduced
in
{Show B}</langsyntaxhighlight>
 
It is possible to introduce multiple variables in a single statement:
<langsyntaxhighlight lang="oz">declare
[A B C D] = [1 2 3 4] %% unification of two lists</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="oz">functor
export Function
define
Line 1,804 ⟶ 3,596:
42
end
end</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="oz">fun {Function Arg}
LocalVar1
in
Line 1,823 ⟶ 3,615:
end
LocalVar1
end</langsyntaxhighlight>
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>.
<langsyntaxhighlight lang="oz">if {IsEven 42} then
{System.showInfo "Here, LocalVar is not visible."}
local
Line 1,834 ⟶ 3,626:
{System.showInfo LocalVar}
end
end</langsyntaxhighlight>
 
New variables are also introduced in pattern matching.
<langsyntaxhighlight lang="oz">case "Rosetta code" of First|_ then {Show First} end %% prints "R"</langsyntaxhighlight>
<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.
<langsyntaxhighlight lang="oz">declare
A
B = !!A %% B is a read-only view of A
Line 1,848 ⟶ 3,640:
B = 43 %% this blocks until A is known; then it fails because 43 \= 42
end
A = 42</langsyntaxhighlight>
 
Additional operations on variables:
<langsyntaxhighlight lang="oz">declare
V = 42
in
Line 1,860 ⟶ 3,652:
elseif {IsFree V} then %% check whether V is free; not recommended
{Show free}
end</langsyntaxhighlight>
<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:
<langsyntaxhighlight lang="oz">declare
A = {NewCell 42}
OldVal
Line 1,870 ⟶ 3,662:
{Show @A} %% read a cell with @
A := 43 %% change its value
OldVal = A := 44 %% read and write at the same time (atomically)</langsyntaxhighlight>
 
<code>A</code> is an immutable dataflow variable that is bound to a mutable reference.
Line 1,876 ⟶ 3,668:
=={{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 ="parigp">'x</langsyntaxhighlight>
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 ="parigp">'x^3+7</langsyntaxhighlight>
is a cubic polynomial, not the number 8, even if x is currently 1.
 
Line 1,888 ⟶ 3,680:
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:
 
<langsyntaxhighlight lang="perl">sub dofruit {
$fruit='apple';
}
 
dofruit;
print "The fruit is $fruit";</langsyntaxhighlight>
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 1,899 ⟶ 3,691:
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.
 
<langsyntaxhighlight lang="perl">my $x = @a; # Scalar assignment; $x is set to the
# number of elements in @a.
my ($x) = @a; # List assignment; $x is set to the first
Line 1,908 ⟶ 3,700:
# 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.</langsyntaxhighlight>
 
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 1,918 ⟶ 3,710:
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:
 
<langsyntaxhighlight lang="perl">use strict;
our $fruit; # declare a variable as global
our $veg = "carrot"; # declare a global variable and define its value</langsyntaxhighlight>
 
=== Local and global variables ===
Line 1,926 ⟶ 3,718:
The following example shows the use of local and global variables:
 
<langsyntaxhighlight lang="perl">$fruit="apple"; # this will be global by default
 
sub dofruit {
Line 1,935 ⟶ 3,727:
 
dofruit;
print "The global fruit is still $fruit";</langsyntaxhighlight>
 
=={{header|Perl 6}}==
Much of what is true for Perl 5 is also true for Perl 6. Some exceptions:
 
There are no typeglobs in Perl 6.
 
Assigning an array to a scalar variable now makes that scalar variable a reference to the array:
 
<lang Perl6>
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
@y[1,2] = 'x','y'; # that's where subscripts and many other things come from
say @y; # OUTPUT«[A x y D]␤» # we start to count at 0 btw.
 
my $x = @y; # $x is now a reference for the array @y
 
say $x[1]; # prints 'x' followed by a newline character
 
my Int $with-type-check; # type checks are enforced by the compiler
 
my Int:D $defined-i = 10; # definedness can also be asked for and default values are required in that case
 
my Int:D $after-midnight where * > 24 = 25; # SQL is fun and so is Perl 6
 
my \bad = 'good'; # if you don't like sigils
say bad; # you don't have to use them
say "this is quite bad"; # but then string interpolation
say "this is quite {bad}" # becomes more wordy
</lang>
 
Laziness is a big topic in Perl 6. Sometimes Perl programmers are so lazy, they can't even be bothered with giving [http://design.perl6.org/S02.html#Names_and_Variables variables names].
 
<lang perl6>say ++$; # this is an anonymous state variable
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;</lang>
 
{{output}}
 
<pre>1
1
2
4
6
12</pre>
 
(Includes code modified from http://design.perl6.org/S02.html#Built-In_Data_Types. See this reference for more details.)
 
=={{header|PL/I}}==
<lang pli>/* The PROCEDURE block and BEGIN block are used to delimit scopes. */
 
declare i float; /* external, global variable, excluded from the */
/* local area (BEGIN block) below. */
begin;
declare (i, j) fixed binary; /* local variable */
get list (i, j);
put list (i,j);
end;
 
/* Examples of initialization. */
 
declare p fixed initial (25);
declare q(7) fixed initial (9, 3, 5, 1, 2, 8, 15);
/* sets all elements of array Q at run time, on block entry. */
declare r(7) fixed initial (9, 3, 5, 1, 2, 8, 15);
/* sets all elements of array R at compile time. */
 
p = 44; /* run-time assignment. */
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. */</lang>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
 
Phix has just five builtin data types:
<pre>
Line 2,027 ⟶ 3,746:
<li>A <b>string</b> can hold a series of characters, or raw binary data.
</ul>
 
 
Unlike traditional statically typed languages, you do not have to remember dozens of possibly complex data types, and unlike a dynamically typed language you get proper
compile-time error messages for simple typos. Phix also allows user defined types, for extra validation and debugging purposes, rather than being fundamentally different to the above.
Line 2,034 ⟶ 3,755:
 
Variables must be declared before use, may be assigned on declaration, and can utilise multiple assignment/sequence decomposition, eg:
 
<lang Phix>integer x = 25, y = 25, z
<!--<syntaxhighlight lang="phix">-->
object {a, b, c} = {{}, 5, "string"}</lang>
<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>
<!--</syntaxhighlight>-->
 
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
the @= ("all equal") operator to assign a, b and c to the same (entire) thing.
Line 2,041 ⟶ 3,766:
Constants are really just variables which must be assigned on declaration and for which subsequent assignment is prohibited.
 
Variables are by default local and restricted to the current file, routine, or block level. Static file-level variables may also be declared as global to make them visible to other source files. There are no static routine or block-level scoped variables, only file-level. Scope resolution is intended to be simple and intuitive, see the link below (Core Language/Declarations/Scope) for more details.
 
User defined types are declared with a single-parameter function that returns true or false, eg:
 
<lang Phix>type hour(integer x)
<!--<syntaxhighlight lang="phix">-->
return x >= 0 and x <= 23
<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>
end type
<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>
hour h1, h2
<span style="color: #008080;">end</span> <span style="color: #008080;">type</span>
h1 = 10 -- ok
<span style="color: #000000;">hour</span> <span style="color: #000000;">h1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">h2</span>
h2 = 25 -- error! program aborts with a message</lang>
<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>
<!--</syntaxhighlight>-->
 
Phix has no notion of unsigned numeric types, except via user defined types such as the above which explicitly prevent their use.
 
You could theoretically write an entire application declaring all variables and parameters as type object, except that it would probably not catch errors the way you might expect it to.
 
An online copy of the manual can be found at http://phix.is-greatx10.orgmx/docs/html/languagephix.htm
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php"><?php
/**
* @author Elad Yosifon
Line 2,219 ⟶ 3,948:
* @url http://php.net/manual/en/resource.php
*/
</syntaxhighlight>
</lang>
 
=={{header|PicoLisp}}==
Line 2,225 ⟶ 3,954:
'[http://software-lab.de/doc/refU.html#use use]' or
'[http://software-lab.de/doc/refL.html#let let]':
<langsyntaxhighlight PicoLisplang="picolisp">(use (A B C)
(setq A 1 B 2 C 3)
... )</langsyntaxhighlight>
This is equivalent to
<langsyntaxhighlight PicoLisplang="picolisp">(let (A 1 B 2 C 3)
... )</langsyntaxhighlight>
The parentheses can be omitted if there is only a single variable
<langsyntaxhighlight PicoLisplang="picolisp">(use A
(setq A ..)
... )
 
(let A 1
...)</langsyntaxhighlight>
Other functions that handle local bindings are
'[http://software-lab.de/doc/refL.html#let? let?]',
Line 2,244 ⟶ 3,973:
'[http://software-lab.de/doc/refW.html#with with]' or
'[http://software-lab.de/doc/refF.html#for for]'.
 
=={{header|PL/I}}==
<syntaxhighlight lang="pli">/* The PROCEDURE block and BEGIN block are used to delimit scopes. */
 
declare i float; /* external, global variable, excluded from the */
/* local area (BEGIN block) below. */
begin;
declare (i, j) fixed binary; /* local variable */
get list (i, j);
put list (i,j);
end;
 
/* Examples of initialization. */
 
declare p fixed initial (25);
declare q(7) fixed initial (9, 3, 5, 1, 2, 8, 15);
/* sets all elements of array Q at run time, on block entry. */
declare r(7) fixed initial (9, 3, 5, 1, 2, 8, 15);
/* sets all elements of array R at compile time. */
 
p = 44; /* run-time assignment. */
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. */</syntaxhighlight>
 
=={{header|Pony}}==
<langsyntaxhighlight Ponylang="pony">var counter: I32 = 10 // mutable variable 'counter' with value 10
let temp: F64 = 36.6 // immutable variable 'temp'
let str: String // immutable variable 'str' with no initial value
Line 2,253 ⟶ 4,006:
 
let b = true
let b' = false // variable names can contain ' to make a distinct variable with almost the same name</langsyntaxhighlight>
 
Destructive read
<langsyntaxhighlight Ponylang="pony">var x: I32 = 10
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</langsyntaxhighlight>
 
=={{header|PowerShell}}==
Variables in PowerShell start with a $ character, they are created on assignment and thus don't need to be declared:
<syntaxhighlight lang="powershell">$s = "abc"
$i = 123</syntaxhighlight>
Uninitialized variables expand to nothing. This may be interpreted for example as an empty string or 0, depending on context:
<syntaxhighlight lang="powershell">4 + $foo # yields 4
"abc" + $foo + "def" # yields "abcdef"</syntaxhighlight>
Variables all show up in the '''Variable''': drive and can be queried from there with the usual facilities:
<syntaxhighlight lang="powershell">Get-ChildItem Variable:</syntaxhighlight>
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="powershell">Remove-Item Variable:foo</syntaxhighlight>
as if it were a file or a registry key. There are, however, several cmdlets dealing specifically with variables:
<syntaxhighlight lang="powershell">Get-Variable # retrieves the value of a variable
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</syntaxhighlight>
 
=={{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:
<langsyntaxhighlight lang="prolog">mortal(X) :- man(X).
man(socrates).</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="prolog">student(X,Y) :- taught(Y,X).
taught(socrates,plato).</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="prolog">?- mortal(socrates).
yes
?- student(X,socrates).
X=plato
?- student(socrates,X).
no</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="prolog">?- mortal(zeus).
no</langsyntaxhighlight>
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
<langsyntaxhighlight lang="prolog">mortal(X) :- man(Y).</langsyntaxhighlight>
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}}==
<langsyntaxhighlight PureBasiclang="purebasic">; Variables are initialized when they appear in sourcecode with default value of 0 and type int
Debug a
; or value "" for a string, they are not case sensitive
Line 2,333 ⟶ 4,104:
; 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</langsyntaxhighlight>
 
=={{header|PowerShell}}==
Variables in PowerShell start with a $ character, they are created on assignment and thus don't need to be declared:
<lang powershell>$s = "abc"
$i = 123</lang>
Uninitialized variables expand to nothing. This may be interpreted for example as an empty string or 0, depending on context:
<lang powershell>4 + $foo # yields 4
"abc" + $foo + "def" # yields "abcdef"</lang>
Variables all show up in the '''Variable''': drive and can be queried from there with the usual facilities:
<lang powershell>Get-ChildItem Variable:</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
<lang powershell>Remove-Item Variable:foo</lang>
as if it were a file or a registry key. There are, however, several cmdlets dealing specifically with variables:
<lang powershell>Get-Variable # retrieves the value of a variable
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</lang>
 
=={{header|Python}}==
Line 2,357 ⟶ 4,110:
 
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.
 
<syntaxhighlight lang="python">
# these examples, respectively, refer to integer, float, boolean, and string objects
example1 = 3
example2 = 3.0
example3 = True
example4 = "hello"
 
# example1 now refers to a string object.
example1 = "goodbye"
</syntaxhighlight>
 
=={{header|Quackery}}==
 
Quackery does not have variables.
 
It is a stack based language, and data items (numbers, names, and nests — i.e. bigints, executable tokens, and dynamic arrays of numbers, names and nests) reside on the Quackery data stack ("the stack") during program execution.
 
Additional data stacks, referred to as ''ancillary stacks'', provide the functionality of global and scoped variables. There are several predefined ancillary stacks, for example <code>base</code>, which stores the current base for numerical i/o, and <code>temp</code>, which is available for use as a local variable. A new named ancillary stack can be defined thus:
 
<pre>[ stack ] is mystack</pre>
 
The following Quackery shell dialogue demonstrates the use of several words relating to ancillary stacks. (<code>ancillary-stack-name copy echo</code> allows us to see the contents of an ancillary stack.)
 
<pre>Welcome to Quackery.
 
Enter "leave" to leave the shell.
 
/O> [ stack ] is A
... [ stack ] is B
... A copy echo cr
... 42 A put
... ' words A put
... ' [ 23 [ over swap ] 801 ] A put
... A copy echo cr
... A take echo cr
... A take echo cr
... A copy echo cr
...
[ stack ]
[ stack 42 words [ 23 [ over swap ] 801 ] ]
[ 23 [ over swap ] 801 ]
words
[ stack 42 ]
 
Stack empty.
 
/O> A share echo cr
... A copy echo cr
...
42
[ stack 42 ]
 
Stack empty.
 
/O> 23 A replace
... A copy echo
...
[ stack 23 ]
Stack empty.
 
/O> -1 A tally
... A copy echo
...
[ stack 22 ]
Stack empty.
 
/O> A B move
... A copy echo cr
... B copy echo cr
... B release
... B copy echo
...
[ stack ]
[ stack 22 ]
[ stack ]
Stack empty.</pre>
 
=={{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.
<langsyntaxhighlight Rlang="r">foo <- 3.4
bar = "abc"</langsyntaxhighlight>
It is possible to assign multiple variables with the same value, and to assign values from left to right.
<langsyntaxhighlight Rlang="r">baz <- quux <- 1:10
TRUE -> quuux</langsyntaxhighlight>
There are also global assignment operators, <<- and ->>. From their help page:
The operators '<<-' and '->>' cause a search to made through the
Line 2,372 ⟶ 4,202:
place in the global environment.
In practice, this usually means that variables are assigned in the user workspace (global environment) rather than a function.
<langsyntaxhighlight Rlang="r">a <- 3
 
assignmentdemo <- function()
Line 2,386 ⟶ 4,216:
message(paste("in the global environment, a = ", get("a", envir=globalenv())))
}
assignmentdemo()</langsyntaxhighlight>
assign 'a' locally, i.e. within the scope of the function
inside assignmentdemo, a = 5
Line 2,394 ⟶ 4,224:
in the global environment, a = 7
Finally, there is also the assign function, where you choose the environment to assign the variable.
<langsyntaxhighlight Rlang="r">assign("b", TRUE) #equivalent to b <- TRUE
assign("c", runif(10), envir=globalenv()) #equivalent to c <<- runif(10)</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 2,446 ⟶ 4,276:
;; racket, structs that are extensions of other structs,
;; pattern-matching on structs, classes, and much more)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
Much of what is true for Perl 5 is also true for Raku. Some exceptions:
 
There are no typeglobs in Raku.
 
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
@y[1,2] = 'x','y'; # that's where subscripts and many other things come from
say @y; # OUTPUT«[A x y D]␤» # we start to count at 0 btw.
 
my $x = @y; # $x is now a reference for the array @y
 
say $x[1]; # prints 'x' followed by a newline character
 
my Int $with-type-check; # type checks are enforced by the compiler
 
my Int:D $defined-i = 10; # definedness can also be asked for and default values are required in that case
 
my Int:D $after-midnight where * > 24 = 25; # SQL is fun and so is Raku
 
my \bad = 'good'; # if you don't like sigils
say bad; # you don't have to use them
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" line>say ++$; # this is an anonymous state variable
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;</syntaxhighlight>
 
{{output}}
 
<pre>1
1
2
4
6
12</pre>
 
(Includes code modified from http://design.raku.org/S02.html#Built-In_Data_Types. See this reference for more details.)
 
=={{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
<langsyntaxhighlight lang="rascal"> Type Name = Exp;</langsyntaxhighlight>
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 2,456 ⟶ 4,336:
 
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 ="rascal">Type Name;</langsyntaxhighlight>
and only introduce the variable Name.
 
Line 2,468 ⟶ 4,348:
 
Two explicit variable declarations:
<langsyntaxhighlight lang="rascal">rascal>int max = 100;
int: 100
rascal>min = 0;
int: 0</langsyntaxhighlight>
 
An implicit variable declaration
<langsyntaxhighlight lang="rascal">rascal>day = {<"mon", 1>, <"tue", 2>, <"wed",3>,
>>>>>>> <"thu", 4>, <"fri", 5>, <"sat",6>, <"sun",7>};
rel[str, int]: {
Line 2,484 ⟶ 4,364:
<"fri",5>,
<"sun",7>
}</langsyntaxhighlight>
 
Variable declaration and assignment leading to type error
<langsyntaxhighlight lang="rascal">rascal>int month = 12;
int: 12
rascal>month ="December";
|stdin:///|(7,10,<1,7>,<1,17>): Expected int, but got str</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="rascal">rascal>if( 4 > 3){ x = "abc"; } else { x = "def";}
str: "abc"
rascal>x;
|stdin:///|(0,1,<1,0>,<1,1>): Undeclared variable, function or constructor: x</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 2,503 ⟶ 4,383:
REXX has only one type of variable: &nbsp; a (character) string.
 
<br>There is no need to declare anything &nbsp; (variables, entry points, subroutines, functions, etc) &nbsp; (indeed, there isisn't noany way to declare anything at all).
 
<br>All unassigned REXX variables have a default value of the variable name (in uppercase).
All unassigned REXX variables have a default value of the variable name (in uppercase).
<br>There is no way to initialize a variable except to assign it a value &nbsp; (by one of the methods below), however,
 
There isn't any way to initialize a variable except to assign it a value &nbsp; (by one of the methods below), however,
<br>there is a way to "initialize" a (stemmed) array in REXX with a default value) ── see the 6<sup>th</sup> section below,
<br>'''default value for an array'''.
 
<br>To assign some data (value) to a variable, one method is to use the assignment operator, an equal sign &nbsp; (<big>'''='''</big>):
<langsyntaxhighlight lang="rexx">aa = 10 /*assigns chars 10 ───► AA */
bb = '' /*assigns a null value ───► BB */
cc = 2*10 /*assigns chars 20 ───► CC */
Line 2,516 ⟶ 4,398:
ee = "Adam" /*same as above ───► EE */
ff = 10. /*assigns chars 10. ───► FF */
gg = '10.' /*same as above ───► GG */
hh = "+10" /*assigns chars +10 ───► hh */
ii = 1e1 /*assigns chars 1e1 ───► ii */
jj = +.1e+2 /*assigns chars .1e+2 ───► jj */</langsyntaxhighlight>
Variables &nbsp; '''aa, &nbsp; ff, &nbsp; gg, &nbsp; hh, &nbsp; ii,''' &nbsp; and &nbsp;'''jj''' &nbsp; will all be considered ''numerically equal'' in REXX &nbsp; (but not exactly equal ''except'' for &nbsp; '''ff''' &nbsp; and &nbsp; '''gg''').
 
===assignments via PARSE===
<langsyntaxhighlight lang="rexx">kk = '123'x /*assigns hex 00000123 ───► KK */
kk = 'dead beaf'X /*assigns hex deadbeaf ───► KK */
ll = '0000 0010'b /*assigns blank ───► LL (ASCII) */
Line 2,540 ⟶ 4,422:
 
cat = 'A cat is a lion in a jungle of small bushes.'
/*assigns a literal ───► CAT */</langsyntaxhighlight>
 
===assignments via VALUE===
Assignments can be made via the &nbsp; '''value''' &nbsp; BIF &nbsp; ['''B'''uilt-'''I'''n '''F'''unction] &nbsp; (which also has other capabilities), the
<br>capability used here is to create a variable name programmatically (normally using concatenation or abuttal).
<langsyntaxhighlight lang="rexx">call value 'CAT', "When the cat's away, the mice will play."
/*assigns a literal ───► CAT */
yyy='CA'
Line 2,552 ⟶ 4,434:
yyy = 'CA'
call value yyy || 'T', "Honest as the Cat when the meat's out of reach."
/*assigns a literal ───► CAT */</langsyntaxhighlight>
 
===unassigned variables===
There are methods to catch unassigned variables in REXX.
<langsyntaxhighlight REXXlang="rexx">/*REXX pgm to do a "bad" assignment (with an unassigned REXX variable).*/
 
signal on noValue /*usually, placed at pgm start. */
Line 2,575 ⟶ 4,457:
say badSource
say
exit 13</langsyntaxhighlight>
Note: &nbsp; the value (result) of the &nbsp; '''condition''' &nbsp; BIF can vary in different implementations of a REXX interpreter. <br>
Line 2,597 ⟶ 4,479:
REXX subroutines/functions/routines/procedures can have their own "local" variables if the &nbsp; '''procedure''' &nbsp; statement is used.
<br>Variables can be shared with the main program if the variables are named on the '''procedure''' statement with the &nbsp; '''expose''' &nbsp; keyword.
<langsyntaxhighlight lang="rexx">/*REXX pgm shows different scopes of a variable: "global" and "local".*/
q = 55 ; say ' 1st q=' q /*assign a value ───► "main" Q.*/
call sub ; say ' 2nd q=' q /*call a procedure subroutine. */
Line 2,614 ⟶ 4,496:
sand: /*all REXX variables are exposed.*/
q = "Monty" ; say 'sand q=' q /*assign a value ───► "global" Q*/
return</langsyntaxhighlight>
'''output'''
<pre>
Line 2,625 ⟶ 4,507:
4th q= Monty
</pre>
Programming note: &nbsp; there is also a method in REXX to '''expose''' a ''list'' of variables. <br>
 
===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.
<langsyntaxhighlight lang="rexx">aaa. = '───────nope.' /*assign this string as a default*/
aaa.1=1 /*assign 1 to first element.*/
aaa.4=4. /* " 4 " fourth " */
Line 2,635 ⟶ 4,517:
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.*/</langsyntaxhighlight>
 
===dropping a variable===
Line 2,644 ⟶ 4,526:
<br>for the REXX language &nbsp; (or for that matter, not even specified), &nbsp; but it's apparently what all &nbsp; (Classic) REXX
<br>interpreters do at the the time of this writing.
<langsyntaxhighlight lang="rexx">radius=6.28 /*assign a value to a variable. */
say 'radius =' radius
drop radius /*now, "undefine" the variable. */
say 'radius =' radius</langsyntaxhighlight>
Note: &nbsp; The value of an undefined (or deallocated) REXX variable is the uppercased name of the REXX variable name. <br>
 
Line 2,663 ⟶ 4,545:
variables' values (which can be any string) with the constants
and the intervening periods.
<langsyntaxhighlight lang="rexx">var.='something' /* sets all possible compound variables of stem var. */
x='3 '
var.x.x.4='something else'
Line 2,669 ⟶ 4,551:
a=left(i,2)
Say i var.a.a.4 "(tail is '"a||'.'||a||'.'||'4'"')"
End</langsyntaxhighlight>
Output:
<pre>
Line 2,683 ⟶ 4,565:
 
Syntax:
<langsyntaxhighlight lang="ring">
<Variable Name> = <Value>
</syntaxhighlight>
</lang>
 
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 2,693 ⟶ 4,575:
Ring is a dynamic programming language that uses Dynamic Typing.
 
<langsyntaxhighlight lang="ring">
x = "Hello" # x is a string
see x + nl
Line 2,710 ⟶ 4,592:
x = false # x is a number (logical value = 0)
see x + nl
</syntaxhighlight>
</lang>
 
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
 
<langsyntaxhighlight lang="ring">
list = [1,2,3,"four","five"]
list2 = list
Line 2,721 ⟶ 4,603:
See "********" + nl
See list2 # print the second list - contains 5 items
</syntaxhighlight>
</lang>
 
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 2,727 ⟶ 4,609:
Rules:
 
<langsyntaxhighlight lang="ring">
<NUMBER> + <STRING> --> <NUMBER>
<STRING> + <NUMBER> --> <STRING>
</syntaxhighlight>
</lang>
 
The same operator ‘+’ can be used as an arithmetic operator or for string concatenation.
 
<langsyntaxhighlight lang="ring">
x = 10 # x is a number
y = "20" # y is a string
Line 2,740 ⟶ 4,622:
Msg = "Sum = " + sum # Msg is a string (sum will be converted to a string)
see Msg + nl
</syntaxhighlight>
</lang>
 
=={{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 2,763 ⟶ 4,663:
Referencing an undefined global or instance variable returns <code>nil</code>. Referencing an undefined local variable throws a <code>NameError</code> exception.
 
<langsyntaxhighlight lang="ruby">$a_global_var = 5
class Demo
@@a_class_var = 6
Line 2,773 ⟶ 4,673:
@an_instance_var += a_local_var
end
end</langsyntaxhighlight>
 
=={{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 2,783 ⟶ 4,714:
 
* '''Local variables''' are variables declared inside a method. Local variables are only accessible from inside the method, but the objects you create may escape the method if you return them from the method. Local variables can be both mutable or immutable types and can be defined using respectively <tt>var</tt> or <tt>val</tt>.
 
=={{header|Seed7}}==
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.
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
var integer: foo is 5; # foo is global
Line 2,800 ⟶ 4,732:
begin
aFunc;
end func;</langsyntaxhighlight>
 
=={{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.
<syntaxhighlight lang="set_lang">set a 0 > Useless intialization - All lowercase variables have an initial value of 0
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
set ? 6 > A "goto" command; Setting the ''?'' variable defines the line of code to be executed next
set z 1 > This line of code will never be executed, because the previous skipped it
set c 10 > Line #5 skipped to here
set d A > Assigning a variable to another variable - ''d'' is now ASCII 65, or the character 'A'
set b ! > The ''!'' deals with I/O. Setting a variable to it receives an input character and assigns it to the variable
set ! a > Setting the exclamation point to a variable outputs that variable
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}}==
 
=== Data Types===
There are two variable data types in smart BASIC; numeric and string.
 
Numeric variables can contain real and complex numbers.
<syntaxhighlight lang="qbasic">x = 14
y = 0.4E3
z = 3-2i</syntaxhighlight>
 
String variables use the dollar symbol ($) at the end.
<syntaxhighlight lang="qbasic">t$ = "Name"</syntaxhighlight>
 
String values may include the quotation symbol " by specifying double quotes "".
<syntaxhighlight lang="qbasic">n$ = """This is a quoted text"""</syntaxhighlight>
 
===Initialization===
Variable names are NOT case sensitive.
 
Variable names may not begin with a number.
 
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.
<syntaxhighlight lang="qbasic">n = 4
a$ = "6 feet"
PRINT n * a$</syntaxhighlight>
{{out}}
<pre>
24
</pre>
 
===Declaration===
Variables do not require declaration in smart BASIC.
 
Only variable arrays need to be declared by size if the array is over 10 elements.
 
Arrays are DIM-ensioned by default with a size of 10. Larger arrays must be pre-DIM-entioned.
<syntaxhighlight lang="qbasic">DIM name$(100)</syntaxhighlight>
 
===Assignment===
The command LET used in standard BASIC may be omitted.
 
'''LET x = 1''' may be shortened to just '''x = 1'''.
 
===Precision===
Numeric variable precision is limited to 64-bit representation with 1 bit for sign, 11 bits for power, and 52 bits for mantissa. Any integer greater than 2^52 (4,503,599,627,370,496) will be approximated.
 
===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).
<syntaxhighlight lang="qbasic">DEF MyFunction(x)
MyF2 = x^2
MyF3 = x^3
MyFunction = MyF2 + MyF3
END DEF</syntaxhighlight>
 
To access the variables within the function:
<syntaxhighlight lang="qbasic">x = MyFunction(3)
PRINT x; MyFunction.MyF2; MyFunction.MyF3</syntaxhighlight>
 
Variables may also be made global using the DEF command:
<syntaxhighlight lang="qbasic">DEF num=123</syntaxhighlight>
 
=={{header|SNOBOL4}}==
Line 2,806 ⟶ 4,814:
Local variables in Snobol are declared in a function definition prototype string:
 
<langsyntaxhighlight SNOBOL4lang="snobol4"> define('foo(x,y)a,b,c') :(foo_end)
foo a = 1; b = 2; c = 3
foo = a * ( x * x ) + b * y + c :(return)
foo_end</langsyntaxhighlight>
 
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.
 
Snobol does not support static or lexical scoping, or module level namespaces. Any variables not defined in a prototype are global to the program.
 
=={{header|SPL}}==
'''Variable declaration.'''
In SPL variables do not need and do not have declaration.
 
'''Initialization.'''
In SPL variables are autodeclared according to their usage. For example, this one-line program is valid because it is evident what is expected:
 
<syntaxhighlight lang="spl">a += 1</syntaxhighlight>
 
In contrast, this one-line program raises an error because it is not evident what object "a" is:
 
<syntaxhighlight lang="spl">a = a+1</syntaxhighlight>
 
'''Assignment.'''
<syntaxhighlight lang="spl">a = 1
b,c,d = 0</syntaxhighlight>
 
'''Datatypes.'''
In SPL an object can be: number, text, stack, array, group, function.
 
'''Scope.'''
There is a main program body scope and individual function scopes. Variable from any scope can be accessed from any other scope by specifying the desired scope and variable name like "scope.variable". Variable from main program body scope can be accessed from any other scope like ".variable", because main program body scope is an empty space.
 
'''Referencing.'''
An object can become a reference to another object using "~" symbol, for example:
 
<syntaxhighlight lang="spl">r = ~a
a = 3
#.output(r)
r = 5
#.output(a)</syntaxhighlight>
 
{{out}}
<pre>
3
5
</pre>
 
=={{header|SSEM}}==
A variable is simply a storage address that the programmer chooses to treat as a variable. It requires no special allocation, declaration, etc., and an initial value can be loaded into it just as with any other storage address. Naturally, there is no concept of scope: any variable can be accessed and modified from any part of the program. To assign a fresh value to a variable, first form the desired number in the accumulator and then use a <tt>110 c to <address></tt> instruction to store it.
 
Note that accessing a value from a variable requires several operations, because the <tt>010 -<address> to c</tt> instruction (corresponding to <tt>load</tt>) negates the value in the process of loading it into the accumulator. The negation must thus be written back into storage and another <tt>010</tt> used to load the negation of that, which is the value we want. Depending on the algorithm, it will be found convenient either to overwrite the variable itself with its negation or to use a separate address as a scratch variable (thus preserving the original).
 
=={{header|SuperCollider}}==
Variables are always local to the scope of a closure or an object.
<syntaxhighlight lang="supercollider">
// variable declaration
var table, chair;
 
// assignment
var table = 10, chair = -10;
 
// multiple assignment to the same value
table = chair = 0;
 
// multiple assignment to an array
(
var table, chair;
#table, chair = [10, -10];
#table ... chair = [10, -10, 2, 3]; // with ellipsis: now chair is [-10, 2, 3]
)
 
// the letters a-z are predeclared in the interpreter for interactive programming
a = 10; x = a - 8;
 
// variables are type-neutral and mutable: reassign to different objects
a = 10; a = [1, 2, 3]; a = nil;
 
// immutable variables (only in class definitions)
const z = 42;
 
// lexical scope
// the closures g and h refer to different values of their c
(
f = {
var c = 0;
{ c = c + 1 }
};
g = f.value;
h = f.value;
c = 100; // this doesn't change it.
)
 
// dynamic scope: environments
f = { ~table = ~table + 1 };
Environment.use { ~table = 100; f.value }; // 101.
Environment.use { ~table = -1; f.value }; // 0.
 
// there is a default environment
~table = 7;
f.value;
 
// lexical scope in environments:
(
Environment.use {
~table = 100;
f = { ~table = ~table + 1 }.inEnvir;
};
)
f.value; // 101.
 
// because objects keep reference to other objects, references are not needed:
// objects can take the role of variables. But there is a Ref object, that just holds a value
 
a = Ref([1, 2, 3]); // a reference to an array, can also be written as a quote `[1, 2, 3];
f = { |x| x.value = x.value.squared }; // a function that operates on a ref
f.(a); // `[ 1, 4, 9 ]
 
// proxy objects serve as delegators in environments. This can be called line by line:
ProxySpace.push;
~z // returns a NodeProxy
~z.play; // play a silent sound
~z = ~x + ~y; // make it the sum of two silent sounds
~x = { PinkNoise.ar(0.1) }; // … which now are noise,
~y = { SinOsc.ar(440, 0, 0.1) }; // and a sine tone
 
</syntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">import Foundation
 
// All variables declared outside of a struct/class/etc are global
Line 2,886 ⟶ 5,012:
 
myFunc = showScopes // myFunc is now showScopes
myFunc() // foo bar function</langsyntaxhighlight>
 
=={{header|Tcl}}==
Line 2,892 ⟶ 5,018:
 
Demonstrating:
<langsyntaxhighlight lang="tcl">namespace eval foo {
# Define a procedure with two formal arguments; they are local variables
proc bar {callerVarName argumentVar} {
Line 2,914 ⟶ 5,040:
unset argumentVar
}
}</langsyntaxhighlight>
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 2,923 ⟶ 5,049:
Variables may be assigned with the <code>→</code> to a value.
 
<langsyntaxhighlight lang="ti83b">
:1→A
</syntaxhighlight>
</lang>
 
=={{header|TI-89 BASIC}}==
Line 2,931 ⟶ 5,057:
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 ="ti89b">Local mynum, myfunc</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="ti89b">Define mynum = 1 © Two ways to assign a number
1 → mynum
 
Line 2,947 ⟶ 5,073:
Return x
EndIf
EndFunc</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT,{}
var1=1, var2="b"
Line 2,965 ⟶ 5,092:
PRINT var,"=",@var
ENDLOOP
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,981 ⟶ 5,108:
Simple example: the <code>cases</code>
 
<langsyntaxhighlight lang="txr">@(cases)
hey @a
how are you
Line 2,987 ⟶ 5,114:
hey @b
long time no see
@(end)</langsyntaxhighlight>
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:
 
<langsyntaxhighlight lang="txr">@(maybe)
@a bar
@(or)
foo @b
@(end)</langsyntaxhighlight>
 
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.
 
=={{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
 
Proc _Initialize(24)
 
_Initialize Param (1)
Local (1) ' A@ now holds 24
B@ = 23 ' local variable
Return
 
' Assignment
A = 15 ' global variable
 
Proc _Assign(24)
 
_Assign Param (1)
Local (1) ' A@ now holds 24
A@ = 5 ' reassignment of parameter A@
B@ = 23 ' local variable
Return</syntaxhighlight>
 
=={{header|UNIX Shell}}==
Line 3,004 ⟶ 5,154:
{{works with|Bourne Shell}}
 
<syntaxhighlight lang="sh">
<lang sh>
#!/bin/sh
# The unix shell uses typeless variables
Line 3,011 ⟶ 5,161:
pears = `expr 5+4` # We use the external expr to perform the calculation
myfavourite="raspberries"
</syntaxhighlight>
</lang>
 
=={{header|Ursa}}==
<syntaxhighlight lang="ursa"># variable declaration
#
# declare [type] [name]
# -or-
# decl [type] [name]
decl int test
 
# initialization / assignment
#
# the set statement can be used to init variables and
# assign values to them
set test 10
 
# datatypes
#
# ursa currently has 10 built-in types, but
# more may be added in the future.
# boolean
# double
# file
# function
# int
# iodevice
# port
# serverport
# string
# task
#
# also, java classes may be used as data types
# cygnus/x ursa
 
# scope
#
# there is a global variable space, and functions
# have their own scope. control statements (for,
# if, try, while) don't have their own scope yet,
# but this will be implemented in the near future
 
# referencing
#
# variables are referenced by their name
decl port p
out p endl console</syntaxhighlight>
 
=={{header|VBA}}==
<br>'''Data types'''<br>
<p>
<table border>
<tr bgcolor="#C0C0C0"><th>Data type<th>Runtime<br>type<th>Category<th>Storage<br>allocation<th>Value range
<tr><td>Boolean<td>Boolean<td><td>1 byte<td>True or False
<tr><td>Integer<td>Int16<td>signed<br>integer<td>2 bytes<td>-32768 through 32767
<tr><td>Long<td>Int32<td>signed<br>long integer<td>4 bytes<td>-2,1E+9 through 2,1E+9
<br>precision: 9 decimals
<tr><td>Byte<td>UInt8<td>unsigned<br>byte<td>1 byte<td>0 through 255
<tr><td>Single<td>Single<td>single precision<br>floating point<td>4 bytes
<td>-3.45E+38 through -1.4E-45 for negative values;
<br>1.4E-45 through 3.4E+38 for positive values;
<br>precision: 6 decimals
<tr><td>Double<td>Double<td>double precision<br>floating point<td>8 bytes
<td>-1.7E+308 through -4.9E-324 for negative values;
<br>4.9E-324 through 1.7E+308 for positive values;
<br>precision: 16 decimals
<tr><td>Currency<td>Decimal<td>extended precision<br>fixed point<td>8 bytes
<td>-922,337,203,685,477.5808 to 922,337,203,685,477.5807
<br>0 through &plusmn;9.2E14
<br>smallest nonzero number is 0.0001;
<tr><td>String(n)<td>String<td>fixed length<br>string<td>n bytes<td>
<tr><td>String<td>String<td>variable length<br>string<td>10+(string length)<td>
<tr><td>Date<td>DateTime<td><td>8 bytes<td>00:00:00 AM on January 1, 0001 through<br>11:59:59 PM on December 31, 9999
<tr><td>Variant<td>Variant<td><td>4 bytes<td>Stores any type of data
</table>
 
=={{header|VBScript}}==
<br>'''Data types'''<br>
<p>VBScript has only one data type called a Variant.
<br>
<table border>
<tr height=200 bgcolor="#C0C0C0"><th>Subtype<th>Category<th>Value range
<tr><td>Boolean<td><td>True or False
<tr><td>Integer<td>signed<br>integer<td>-32768 through 32767
<tr><td>Long<td>signed<br>long integer<td>-2,1E+9 through 2,1E+9<br>precision: 9 decimals
<tr><td>Byte<td>unsigned<br>byte<td>0 through 255
<tr><td>Single<td>single precision<br>floating point
<td>-3.45E+38 through -1.4E-45 for negative values;<br>1.4E-45 through 3.4E+38 for positive values;<br>precision: 6 decimals
<tr><td>Double<td>double precision<br>floating point
<td>-1.7E+308 through -4.9E-324 for negative values;<br>4.9E-324 through 1.7E+308 for positive values;<br>precision: 16 decimals
<tr><td>Currency<td>extended precision<br>fixed point
<td>-922,337,203,685,477.5808 to 922,337,203,685,477.5807<br>0 through &plusmn;9.2E14<br>smallest nonzero number is 0.0001;
<tr><td>String<td>variable length<br>string<td>
<tr><td>Date<td><td>00:00:00 AM on January 1, 0001 through<br>11:59:59 PM on December 31, 9999
<tr><td>Object<td><td>Stores any object reference
<tr><td>Empty<td><td>Variant is uninitialized
<tr><td>Null<td><td>Variant has no valid data
<tr><td>Error<td><td>Variant contains an error number
</table>
 
=={{header|Visual Basic}}==
<br>'''Data types'''<br>
<p>
<table border>
<tr bgcolor="#C0C0C0"><th>Data type<th>Runtime<br>type<th>Category<th>Storage<br>allocation<th>Value range
<tr><td>Boolean<td>Boolean<td><td>1 byte<td>True or False
<tr><td>Integer<td>Int16<td>signed<br>integer<td>2 bytes<td>-32768 through 32767
<tr><td>Long<td>Int32<td>signed<br>long integer<td>4 bytes<td>-2,1E+9 through 2,1E+9
<br>precision: 9 decimals
<tr><td>Byte<td>UInt8<td>unsigned<br>byte<td>1 byte<td>0 through 255
<tr><td>Single<td>Single<td>single precision<br>floating point<td>4 bytes
<td>-3.45E+38 through -1.4E-45 for negative values;
<br>1.4E-45 through 3.4E+38 for positive values;
<br>precision: 6 decimals
<tr><td>Double<td>Double<td>double precision<br>floating point<td>8 bytes
<td>-1.7E+308 through -4.9E-324 for negative values;
<br>4.9E-324 through 1.7E+308 for positive values;
<br>precision: 16 decimals
<tr><td>Currency<td>Decimal<td>extended precision<br>fixed point<td>8 bytes
<td>-922,337,203,685,477.5808 to 922,337,203,685,477.5807
<br>0 through &plusmn;9.2E14
<br>smallest nonzero number is 0.0001;
<tr><td>String(n)<td>String<td>fixed length<br>string<td>n bytes<td>
<tr><td>String<td>String<td>variable length<br>string<td>10+(string length)<td>
<tr><td>Date<td>DateTime<td><td>8 bytes<td>00:00:00 AM on January 1, 0001 through<br>11:59:59 PM on December 31, 9999
<tr><td>Variant<td>Variant<td><td>4 bytes<td>Stores any type of data
<tr><td>Object<td>Object<td><td>4 bytes<td>Stores any object reference
</table>
 
=={{header|Visual Basic .NET}}==
 
<br>'''Variable declaration'''<br>
<syntaxhighlight lang="vbnet">Dim variable As datatype
Dim var1,var2,... As datatype</syntaxhighlight>
example:
<syntaxhighlight lang="vbnet">Dim n1,n2 as Integer
Dim x as Double
Dim isRaining as Boolean
Dim greeting as String</syntaxhighlight>
 
<br>'''Initialization'''<br>
<syntaxhighlight lang="vbnet">Dim variable As datatype = value
Dim var1,var2,... As datatype</syntaxhighlight>
example:
<syntaxhighlight lang="vbnet">Dim wholeNumber1,wholeNumber2 as Integer = 3
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}}</syntaxhighlight>
 
<br>'''Assignment'''<br>
<syntaxhighlight lang="vbnet">variable = expression</syntaxhighlight>
<syntaxhighlight lang="vbnet"> v = a
d = b^2 - 4*a*c
s3 = s1 & mid(s2,3,2)</syntaxhighlight>
<syntaxhighlight lang="vbnet">variable <operator>= expression2</syntaxhighlight>
<syntaxhighlight lang="vbnet"> c += a
c -= a
c *= a
c /= a
c ^= a
c <<= n
c >>= n
c &= a</syntaxhighlight>
 
<br>'''Data types'''<br>
<p>
<table border>
<tr bgcolor="#C0C0C0"><th>Data type<th>Runtime<br>type<th>Category<th>Storage<br>allocation<th>Value range
<tr><td>Boolean<td>Boolean<td><td>1 byte<td>True or False
<tr><td>Char<td>Char<td>unsigned<td>2 bytes<td>0 through 65535
<tr><td>SByte<td>Int8<td>signed<br>byte<td>1 byte<td>-128 through 127
<tr><td>Short<td>Int16<td>signed<br>short integer<td>2 bytes<td>-32,768 through 32,767
<tr><td>Integer<td>Int32<td>signed<br>integer<td>4 bytes<td>-2,1E+9 through 2,1E+9<br>precision: 9 decimals
<tr><td>Long<td>Int64<td>signed<br>long integer<td>8 bytes<td>-9.2E+18 through 9.2E+18<br>precision: 18 decimals
<tr><td>Byte<td>UInt8<td>unsigned<br>byte<td>1 byte<td>0 through 255
<tr><td>UShort<td>UInt16<td>unsigned<br>short integer<td>2 bytes<td>0 through 65,535
<tr><td>UInteger<td>UInt32<td>unsigned<br>integer<td>4 bytes<td>0 through 4,2E+9
<tr><td>ULong<td>UInt64<td>unsigned<br>long integer<td>8 bytes<td>0 through 1.8E+19
<tr><td>Single<td>Single<td>single precision<br>floating point<td>4 bytes
<td>-3.45E+38 through -1.4E-45 for negative values;<br>1.4E-45 through 3.4E+38 for positive values;<br>precision: 6 decimals
<tr><td>Double<td>Double<td>double precision<br>floating point<td>8 bytes
<td>-1.7E+308 through -4.9E-324 for negative values;<br>4.9E-324 through 1.7E+308 for positive values;<br>precision: 16 decimals
<tr><td>Decimal<td>Decimal<td>extended precision<br>fixed point<td>16 bytes
<td>0 through &plusmn;7.9E+28 with no decimal point;<br>0 through &plusmn;7.9 with 28 places to the right of the decimal;<br>smallest nonzero number is &plusmn;1E-28;<br>precision: 28 decimals
<tr><td>String<td>String<td>variable length<br>string<td><td>
<tr><td>Date<td>DateTime<td><td>8 bytes<td>00:00:00 AM on January 1, 0001 through<br>11:59:59 PM on December 31, 9999
<tr><td>Object<td>Object<td><td>4 bytes on<br>32-bit platform<br>8 bytes on<br>64-bit platform
<td>
</table>
 
<br>'''scope'''<br>
By default the scope of a variable is local to the <code>sub</code>, <code>function</code> or <code>module</code>.
By default the scope of a <code>sub</code> or <code>function</code> is global to the project.
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)</syntaxhighlight>
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.
 
The variable's type is inferred from the value on the right hand side. To choose a different type, use type conversion: the expression T(v) converts the value v to the type T.
 
Unlike most other languages, V only allows defining variables in functions. Global (module level) variables are not allowed. There's no global state in V (see Pure functions by default for details).
 
For consistency across different code bases, all variable and function names must use the snake_case style, as opposed to type names, which must use PascalCase.
 
'''Mutable variables'''
<syntaxhighlight lang="v (vlang)">mut age := 20
println(age) // 20
age = 21
println(age) // 21</syntaxhighlight>
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.
 
'''Initialization vs assignment'''
Note the (important) difference between := and =. := is used for declaring and initializing, = is used for assigning.
 
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</syntaxhighlight>
'''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 {
a := 20 // error: redefinition of `a`
}
// warning: unused variable `a`
}</syntaxhighlight>
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.
 
=={{header|WDTE}}==
 
WDTE does not have variables, per se, but it does have several things that work similarly. The most obvious is function parameters:
 
<syntaxhighlight lang="wdte">let example t => io.writeln io.stdout t;</syntaxhighlight>
 
The parameters are scoped to the inside of the function in which they're declared. There are also lambdas, which also have parameters:
 
<syntaxhighlight lang="wdte">let example t => 3 -> (@ s n => * t n);</syntaxhighlight>
 
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.
 
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:
 
<syntaxhighlight lang="wdte">let writeToFile name data =>
file.open name : f
-> str.format '{}' data
-> io.writeln f
-- io.close f
;</syntaxhighlight>
 
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.
 
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:
 
<syntaxhighlight lang="wdte">let a => 3;
io.writeln io.stdout a;</syntaxhighlight>
 
=={{header|Wren}}==
Wren is dynamically typed and variables can be assigned or reassigned values of any type.
 
If a variable is declared but not assigned a value, it is given the special value 'null'.
 
A variable can only be declared once for a given scope (top level, block, function, method etc.) but the same variable name can be reused in a nested scope in which case it will hide the variable in the outer scope.
 
Depending on the type of value assigned, a variable can either hold the value directly (value type) or a reference to where an object is stored in memory (reference type). Values of the built-in types: Num, Bool and Null are value types and all other types are reference types. However, values of the built-in String, Class and Range types are immutable and are always copied/compared by value rather than by reference. Consequently they behave as though they were value types.
 
Here are a few examples.
<syntaxhighlight lang="wren">var a // declares the variable 'a' with the default value of 'null'
a = 1 // initializes 'a'
a = "a" // assigns a different value to 'a'
var b = 2 // declares and initializes 'b' at the same time
b = true // assigns a different value to 'b'
var c = [3, 4] // 'c' is assigned a List which is a reference type
c = false // 'c' is reassigned a Bool which is a value type
 
var d = 1 // declaration at top level
{
var d = 2 // declaration within a nested scope, hides top level 'd'
var e = 3 // not visible outside its scope i.e this block
}
System.print(d) // prints the value of the top level 'd'
System.print(e) // compiler error : Variable is used but not defined</syntaxhighlight>
 
=={{header|XPL0}}==
Line 3,046 ⟶ 5,483:
=={{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.
<langsyntaxhighlight lang="xml"><xsl:variable name="foo" select="XPath expression" />
<xsl:if test="$foo = 4">... </xsl:if> <!-- prepend '$' to reference a variable or parameter--></langsyntaxhighlight>
 
=={{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.
<syntaxhighlight lang="z80">UserRam equ &C000
 
ld a,&50 ;load hexadecimal 50 into A
ld (UserRam),a ;initialize UserRam with a value of &50
 
ld a,&40 ;load hexadecimal 40 into A
ld (UserRam),a ;assign UserRam a new value of &40</syntaxhighlight>
 
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:
 
<syntaxhighlight lang="z80">byte &EF,&BE
word &BEEF</syntaxhighlight>
 
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:
 
<syntaxhighlight lang="z80">org &8000
 
ld hl,TestData ;H = &90, L = &00
 
ld hl,(TestData) ;H = &BE, L = &EF
 
;In a real program you would need something here to stop the program counter from executing the data below as instructions.
;For simplicity this was left out.
 
org &9000
TestData:
byte &EF,&BE</syntaxhighlight>
 
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.
 
=={{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.
<langsyntaxhighlight lang="zkl">var v; // global to the class that encloses this file
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 3,064 ⟶ 5,533:
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</langsyntaxhighlight>
 
 
Line 3,074 ⟶ 5,543:
[[Category:Initialization]]
[[Category:Scope]]
 
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">program: variables
# 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}}==
[http://zoea.co.uk/examples/zv-rc/Variables.png Variables]
1,150

edits