Variables: Difference between revisions

48,906 bytes added ,  1 month ago
m
No edit summary
 
(35 intermediate revisions by 18 users not shown)
Line 15:
=={{header|11l}}==
To declare <code>a</code> as an integer:
<syntaxhighlight lang ="11l">Int a</langsyntaxhighlight>
 
Type of variables may be inferred:
<langsyntaxhighlight lang="11l">V a = 1</langsyntaxhighlight>
 
Multiple variables may be defined in a single line as follows:
<syntaxhighlight lang ="11l">Int p, a, d</langsyntaxhighlight>
 
=={{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 55 ⟶ 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 73 ⟶ 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">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program variable64.s */
Line 138 ⟶ 245:
qAdriInteger2: .quad iInteger2 // variable address iInteger2
 
</syntaxhighlight>
</lang>
 
=={{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 159 ⟶ 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 194 ⟶ 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 201 ⟶ 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 referred 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 225 ⟶ 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 232 ⟶ 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 248 ⟶ 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 272 ⟶ 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">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program variable.s */
Line 340 ⟶ 447:
iAdriInteger2: .int iInteger2 @ variable address iInteger2
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">num: 10
str: "hello world"
 
Line 359 ⟶ 466:
]
 
inspect symbols</langsyntaxhighlight>
 
=={{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 371 ⟶ 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 394 ⟶ 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 408 ⟶ 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 414 ⟶ 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 433 ⟶ 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 447 ⟶ 554:
foo(s,k)
print "k still is", k
}</langsyntaxhighlight>
{{Out}}
<pre>
Line 465 ⟶ 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 481 ⟶ 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 494 ⟶ 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 509 ⟶ 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}}===
Line 516 ⟶ 623:
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 530 ⟶ 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}}===
Line 567 ⟶ 674:
'''Demonstration Program'''
 
<langsyntaxhighlight 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
Line 688 ⟶ 795:
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</langsyntaxhighlight>
 
'''Modifications for Enhanced TIME$'''
Line 694 ⟶ 801:
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):
 
<langsyntaxhighlight 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)
Line 705 ⟶ 812:
5515 print chr$(19);"Time: "t$
5520 get k$:if k$="" then 5510
5525 print chr$(147);:return</langsyntaxhighlight>
 
==={{Header|Tiny BASIC}}===
<langsyntaxhighlight lang="tiny basic">REM Tiny Basic has exactly 26 variables.
REM They start off initialised to zero.
PRINT A
Line 737 ⟶ 844:
 
REM Tiny Basic does not support arrays or pointers. Strings can
REM be used, but only as string constants within a PRINT statement.</langsyntaxhighlight>
 
=={{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 759 ⟶ 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 795 ⟶ 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|Boo}}==
Line 851 ⟶ 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.
<langsyntaxhighlight lang="bracmat">(myfunc=i j.!arg:(?i.?j)&!i+!j)</langsyntaxhighlight>
Global variables are created the first time they are assigned a value.
 
Line 880 ⟶ 1,002:
=={{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.
Line 903 ⟶ 1,025:
 
They are declared with the type first, as in C:
<syntaxhighlight lang ="csharp">int j;</langsyntaxhighlight>
 
Multiple variables may be defined in a single line as follows:
<syntaxhighlight lang ="csharp">int p, a, d;</langsyntaxhighlight>
 
It is also possible to assign variables, either while declaring or in the program logic:
<langsyntaxhighlight lang="csharp">int a = 4;
int b;
int c = Func(a);
 
b = 5;</langsyntaxhighlight>
 
=={{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;</langsyntaxhighlight>
From C++11, type of variables may be inferred:
<langsyntaxhighlight lang="cpp">auto a = 1; // int a = 1</langsyntaxhighlight>
 
Template variables are specified with template parameters in angle brackets after the class name:
<syntaxhighlight lang ="cpp">std::vector<int> intVec;</langsyntaxhighlight>
 
=={{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 936 ⟶ 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|Clojure}}==
Line 966 ⟶ 1,088:
 
'''Declaration only:'''
<syntaxhighlight lang ="lisp">(declare foo)</langsyntaxhighlight>
<syntaxhighlight lang ="lisp">(def bar)</langsyntaxhighlight>
 
'''Global scope initialization:'''
<syntaxhighlight lang ="lisp">(def foo 42)</langsyntaxhighlight>
<syntaxhighlight lang ="lisp">(defonce bar 42)</langsyntaxhighlight>
<langsyntaxhighlight lang="lisp">(defn baz [x] 42)</langsyntaxhighlight>
<langsyntaxhighlight lang="lisp">(defmacro qux [x] 42)</langsyntaxhighlight>
 
'''Local scope initialization:'''
<langsyntaxhighlight lang="lisp">(let [foo 42] ...)</langsyntaxhighlight>
 
'''Local re-binding of dynamic global var:'''
<langsyntaxhighlight lang="lisp">(def ^:dynamic foo 10)
(binding [foo 20] ...)</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="lisp">(defn len [^String x]
(.length x))</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="lisp">(def foo (atom 42))</langsyntaxhighlight>
<langsyntaxhighlight lang="lisp">(def bar (ref 42))</langsyntaxhighlight>
<langsyntaxhighlight lang="lisp">(def baz (agent 42))</langsyntaxhighlight>
 
=={{header|COBOL}}==
Line 996 ⟶ 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 1,020 ⟶ 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 1,034 ⟶ 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 1,044 ⟶ 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 1,058 ⟶ 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 1,084 ⟶ 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 1,090 ⟶ 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>
 
'''defconstant''' works in the same way, but binds a constant. Constants are wrapped with '+' signs rather than earmuffs.
Line 1,102 ⟶ 1,224:
For local 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 1,112 ⟶ 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 1,123 ⟶ 1,245:
We use '''setf''' to modify the value of a symbol.
 
<syntaxhighlight lang ="lisp">(setf *x* 625)</langsyntaxhighlight>
 
We can also modify multiple symbols sequentially:
 
<langsyntaxhighlight lang="lisp">(setf *x* 42 *y* (1+ *x*))
=>43</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="lisp">(setf *x* 625)
(psetf *x* 42 *y* (1+ *x*)
=>NIL</langsyntaxhighlight>
 
The return value is NIL, but the resulting value of '''*y*''' is 626 instead of 43.
Line 1,141 ⟶ 1,263:
Common Lisp is dynamically typed, so we don't have to explicitly tell it what type of value a symbol holds. We nonetheless have the option of being explicit about which types our functions use through '''ftype''' declarations, which tell the compiler what to expect:
 
<langsyntaxhighlight lang="lisp">(declaim (ftype (function (fixnum) fixnum) frobnicate))
(defun frobnicate (x)
(+ x 42))</langsyntaxhighlight>
 
In this example, the function '''frobnicate''' must be written to take one fixnum (i.e., a fixed-width integer as opposed to a bignum) and must return a fixnum. Having been given this type information, the compiler can now assert that the function works the way we've told it it does, and will throw an error when you've made a mistake in implementing or calling the function. The compiler may also use more performant fixnum-specific arithmetic functions instead of the generic arithmetic functions.
Line 1,149 ⟶ 1,271:
You can give the compiler the same information using in-function type declarations and the '''the''' operator:
 
<langsyntaxhighlight 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.
 
=={{header|D}}==
<syntaxhighlight lang="d">
<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>
</lang>
 
=={{header|DBL}}==
<syntaxhighlight lang="dbl">;
<lang DBL>;
; Variables examples for DBL version 4 by Dario B.
;
Line 1,235 ⟶ 1,357:
ALPA1[2,1](3,4)="FO"
;.....................
</syntaxhighlight>
</lang>
 
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">var
<lang Delphi>var
i: Integer;
s: string;
Line 1,251 ⟶ 1,373:
o.Free;
end;
end;</langsyntaxhighlight>
 
=={{header|DM}}==
Line 1,257 ⟶ 1,379:
 
Declaring variables:
<langsyntaxhighlight DMlang="dm">// Both of the following declarations can be seen as a tree,
// var -> <varname>
var/x
Line 1,269 ⟶ 1,391:
// And like this, still a tree structure.
var/x, y
</syntaxhighlight>
</lang>
 
The type of a variable can be declared like this, note that there is are types for strings or numbers:
 
<langsyntaxhighlight DMlang="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:
Line 1,285 ⟶ 1,407:
// ...
// You get the idea
</syntaxhighlight>
</lang>
 
Variables can be assigned, during declaration or later. The compiler does not enforce types here at all.
 
<syntaxhighlight lang="dm">
<lang DM>
var/x = 0
x = 10
var/y
y = "hi!"
</syntaxhighlight>
</lang>
 
=={{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 1,300 ⟶ 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}}==
 
<langsyntaxhighlight Dyalectlang="dyalect">//A constant declaration
let PIpi = 3.14
private {
Line 1,354 ⟶ 1,733:
base.x
}
}</langsyntaxhighlight>
 
=={{header|E}}==
Line 1,362 ⟶ 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 1,370 ⟶ 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 1,378 ⟶ 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 1,384 ⟶ 1,763:
def var list := ["x"]
list with= "y" # equivalent to list := list.with("y")
list # returns ["x", "y"]</langsyntaxhighlight>
 
'''Patterns'''
Line 1,390 ⟶ 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 1,400 ⟶ 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 1,407 ⟶ 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 1,416 ⟶ 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 1,427 ⟶ 1,806:
var idc := 0
getUniqueId(&idc) # returns 1
getUniqueId(&idc) # returns 2</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">
<lang># it is statically typed
# it is statically typed
#
# global number variable
Line 1,439 ⟶ 1,819:
a[] = [ 2.1 3.14 3 ]
#
funcproc ffoo . .
# i is local, because it is first used in the function
for i range= 1 to len a[]
print a[i]
.
.
foo
call f
#
# string
domain$ = "easylang.onlinedev"
print domain$
#
# array of strings
fruits$[] = [ "apple" "banana" "orange" ]
print fruits$[]</lang>
</syntaxhighlight>
 
=={{header|Eiffel}}==
Variables must be declared before their use with an explicit type.
<langsyntaxhighlight lang="eiffel">
class
APPLICATION
Line 1,481 ⟶ 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 1,491 ⟶ 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 1,504 ⟶ 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:
<langsyntaxhighlight lang="elena">import system'collections;
 
public program()
Line 1,528 ⟶ 1,909:
 
c := b + a; // assigning variable
}</langsyntaxhighlight>
 
=={{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 1,565 ⟶ 1,946:
a b + number>string print ;
 
: local-example ( -- str ) [let "a" :> b "c" :> a a " " b 3append ] ;</langsyntaxhighlight>
 
=={{header|Falcon}}==
<langsyntaxhighlight lang="falcon">
/* partially created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
Line 1,595 ⟶ 1,976:
/* There are plenty more
data types in Falcon */
</syntaxhighlight>
</lang>
 
=={{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 1,629 ⟶ 2,010:
=={{header|Fortran}}==
 
<langsyntaxhighlight lang="fortran"> program test
implicit none
 
Line 1,657 ⟶ 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,684 ⟶ 2,180:
IsBound(u[3]);
# false
Unbind(u[4]);</langsyntaxhighlight>
 
=={{header|GlovePIE}}==
<langsyntaxhighlight GlovePIElang="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.
Line 1,695 ⟶ 2,191:
// var.example1 now refers to a string object instead.
var.variable1="Bye!"
endif</langsyntaxhighlight>
 
=={{header|Go}}==
Line 1,701 ⟶ 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,722 ⟶ 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,750 ⟶ 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,759 ⟶ 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,769 ⟶ 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,779 ⟶ 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,812 ⟶ 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,849 ⟶ 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;</langsyntaxhighlight>
 
Some common types are: <i>I8, I64, U8, U64, F64</i>.
Line 1,859 ⟶ 2,355:
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="holyc">U8 b1 = 8;
U8 b2 = b1 * 10;</langsyntaxhighlight>
 
Multiple variables may be defined in a single statement as follows:
<syntaxhighlight lang ="holyc">U8 uint1, uint2, uint3;</langsyntaxhighlight>
 
To initialized a string:
<langsyntaxhighlight lang="holyc">U8 *str = "The HolyC Language";</langsyntaxhighlight>
 
== Icon and Unicon ==
Line 1,872 ⟶ 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,884 ⟶ 2,380:
 
# ... rest of program
end</langsyntaxhighlight>
 
==={{header|Icon}}===
Line 1,892 ⟶ 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,907 ⟶ 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,934 ⟶ 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,958 ⟶ 2,462:
final Date now = new java.util.Date();
now.setTime(1234567890); //legal
now = new Date(1234567890); //not legal</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 1,969 ⟶ 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 2,035 ⟶ 2,539:
six();
alert(new Seven().a);
alert(new Seven().b);</langsyntaxhighlight></div>
 
=={{header|Joy}}==
Line 2,043 ⟶ 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 2,054 ⟶ 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 2,065 ⟶ 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 2,071 ⟶ 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.
 
Line 2,087 ⟶ 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 2,101 ⟶ 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}}==
Line 2,115 ⟶ 2,619:
 
Here are some examples of local variables:
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun main(args: Array<String>) {
Line 2,140 ⟶ 2,644:
 
println("$i, $d, $sh, $ch, $bt, $s, $l, $b, $f")
}</langsyntaxhighlight>
 
{{out}}
Line 2,149 ⟶ 2,653:
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
<lang Scheme>
1) working in a global scope
 
Line 2,172 ⟶ 2,676:
} // closing local scope
-> 12
</syntaxhighlight>
</lang>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">// declare thread variable, default type null
var(x)
$x->type // null
Line 2,215 ⟶ 2,719:
'\r'
#copy // unmodified as it used ascopydeep
//array(RADISH, CARROT, CUCUMBER, OLIVE)</langsyntaxhighlight>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
'In Liberty BASIC variables are either string or numeric.
'A variable name can start with any letter and it can contain both letters and numerals, as well as dots (for example: user.firstname).
Line 2,248 ⟶ 2,752:
'They can be declared 'global' if such visibility is desired.
'Functions can receive variables by name or by reference.
</syntaxhighlight>
</lang>
 
=={{header|Lingo}}==
In Lingo (local) variables are declared by assigning a value:
<langsyntaxhighlight lang="lingo">x = 23
y = "Hello world!"
z = TRUE -- same effect as z = 1</langsyntaxhighlight>
 
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":
<langsyntaxhighlight lang="lingo">on foo
put x
end</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="lingo">put value("x")
-- <Void> -- means: undefined</langsyntaxhighlight>
 
But variable declarations/assignments can also explicitely assign the constant VOID. The following script compiles successfully, but value("x") would still return <Void>:
<langsyntaxhighlight lang="lingo">on foo
x = VOID
put x
end</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="lingo">global x
on foo
put x
end</langsyntaxhighlight>
<langsyntaxhighlight lang="lingo">on foo
global x
put x
end</langsyntaxhighlight>
 
Global variables can also be declared/created at runtime, by adding them as property to the special _global object:
<langsyntaxhighlight lang="lingo">_global.x = 23</langsyntaxhighlight>
 
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</langsyntaxhighlight>
 
=={{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 2,309 ⟶ 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 2,325 ⟶ 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|M2000 Interpreter}}==
Line 2,348 ⟶ 2,852:
 
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
\\ M2000 use inference to state the type of a new variable, at run time
\\ We can use literals of a numeric type
Line 2,444 ⟶ 2,948:
}
If Error or Not Ok then Print Error$ ' we get wrong data type
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
Line 2,450 ⟶ 2,954:
 
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.
<langsyntaxhighlight lang="maple">a := 1:
print ("a is "||a);
"a is 1"</langsyntaxhighlight>
 
 
Line 2,459 ⟶ 2,963:
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.
<langsyntaxhighlight lang="maple">b;
f := proc()
local b := 3;
Line 2,468 ⟶ 2,972:
b
"b is 3"
"b is b"</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="maple">f := proc()
global c;
c := 3;
Line 2,482 ⟶ 2,986:
"a is 1"
"c is 3"
"c is 3"</langsyntaxhighlight>
 
 
Variables can be reassigned.
<langsyntaxhighlight lang="maple">print ("a is "||a);
a := 4:
print ("a is "||a);
"a is 1"
"a is 4"</langsyntaxhighlight>
 
 
Variables can be reassigned as different datatypes.
<langsyntaxhighlight lang="maple">print ("a is "||a);
type(a, integer);
a := "Hello World":
Line 2,504 ⟶ 3,008:
"a is Hello World"
false
true</langsyntaxhighlight>
 
 
Variable names may contain spaces and other characters when you enclose them in ``.
<langsyntaxhighlight lang="maple">`This is a variable` := 1:
print(`This is a variable`);
1</langsyntaxhighlight>
 
 
To unassign a variable.
<langsyntaxhighlight lang="maple">print ("a is "||a);
type(a, string);
print("c is "||c);
Line 2,527 ⟶ 3,031:
"a is a"
true
"c is c"</langsyntaxhighlight>
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 2,583 ⟶ 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 2,599 ⟶ 3,103:
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}}==
Line 2,609 ⟶ 3,113:
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:
 
<langsyntaxhighlight Mercurylang="mercury">:- func name = string.
name = Name :-
Name = Title ++ " " ++ Given,
Title = "Dr.",
Given = "Bob".</langsyntaxhighlight>
 
Mercury also has state variables, actually pairs of variables, usually instantiated in the head of a rule.
 
<langsyntaxhighlight Mercurylang="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).</langsyntaxhighlight>
 
In this example <code>!IO</code> is the state variable, and this code translates to
 
<langsyntaxhighlight Mercurylang="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).</langsyntaxhighlight>
 
which translates roughly to:
 
<langsyntaxhighlight Mercurylang="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).</langsyntaxhighlight>
 
<code>!.IO</code> is the bound 'current value' of IO, <code>!:IO</code> is the free 'next value' of IO, and the lexical appearance of these variables matters to their final translation to the normal variables in the third example, where data dependency enforces the intended order of operation (so that "Hello" is always written before the name.)
Line 2,640 ⟶ 3,144:
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:
 
<langsyntaxhighlight Mercurylang="mercury">:- func dr(string) = string.
dr(Name) = Titled :-
some [!SB] (
Line 2,648 ⟶ 3,152:
format(handle, " %s", [s(Name)], !SB),
Titled = to_string(!.SB)
).</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight Mercurylang="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).</langsyntaxhighlight>
 
In pure Mercury code that only uses functional data types, and only normal functions in higher-order code, variables can be said to be either 'free' or 'ground' where they're found in code, before the goal they're in changes their instantiation (for example to bind a free variable to a value, making it ground). The only exception are the 'state of the world' values used for I/O, which have 'unique' and 'dead' instantiations.
Line 2,663 ⟶ 3,167:
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:
 
<langsyntaxhighlight Mercurylang="mercury">:- type accumulator == (pred(int, int, io, io)).
:- inst accumulator == (pred(in, out, di, uo) is det).
 
Line 2,685 ⟶ 3,189:
>> add(-10),
F(0, X, !IO),
io.print_line(X, !IO).</langsyntaxhighlight>
 
{{out}}
Line 2,695 ⟶ 3,199:
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:
 
<langsyntaxhighlight Mercurylang="mercury">:- module evenodd.
:- interface.
:- import_module io.
Line 2,734 ⟶ 3,238:
SUCCESS_INDICATOR = N == COIN_HEADS;
").
</syntaxhighlight>
</lang>
 
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 2,753 ⟶ 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}}==
<langsyntaxhighlight lang="nanoquery">// variable definition and initialization/assignment
//
// variables are initialized when they are defined
Line 2,812 ⟶ 3,336:
// scope using the 'delete' command
test_var = "pretend this is a really large object we want to free up"
delete test_var</langsyntaxhighlight>
 
=={{header|Nim}}==
Line 2,851 ⟶ 3,375:
6) Examples
 
<langsyntaxhighlight lang="nim">var x: int = 3 # Declaration with type specification and initialization.
 
var y = 3 # Declaration with type inferred to "int".
Line 2,876 ⟶ 3,400:
 
proc q =
echo xloc # Referencing a variable in the enclosing scope.</langsyntaxhighlight>
 
=={{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 2,890 ⟶ 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 2,911 ⟶ 3,435:
let a = 31
and b = 150 in
(a + b)</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 2,930 ⟶ 3,454:
Using -> removes the top of the stack and assign this value to the variable
 
<langsyntaxhighlight Oforthlang="oforth">import: date
 
: testVariable
| a b c |
Date now ->a
a println ;</langsyntaxhighlight>
 
=={{header|ooRexx}}==
While REXX (and ooRexx) normally pass arguments ''by value''. ooRexx has a mechanism to pass compound variables ''by reference''.
<syntaxhighlight lang="text">a.=4711
Say 'before sub a.3='a.3
Call sub a.
Line 2,947 ⟶ 3,471:
use Arg a.
a.3=3
Return</langsyntaxhighlight>
{{out}}
<pre>before sub a.3=4711
Line 2,956 ⟶ 3,480:
Ol is a purely functional Lisp, so there are no variables in common sense in Ol. We use 'symbol' and 'linked value' instead.
 
<langsyntaxhighlight lang="scheme">
; Declare the symbol 'var1' and associate number 123 with it.
(define var1 123)
Line 2,978 ⟶ 3,502:
; ==> 321
; ... function 'show' still print old associated value
</syntaxhighlight>
</lang>
 
Other possible ways to declare a symbol and link value with it: let, let*, letrec, letrec*, define a function.
Line 2,985 ⟶ 3,509:
=={{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 2,993 ⟶ 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 2,999 ⟶ 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 3,006 ⟶ 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 3,033 ⟶ 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 3,052 ⟶ 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 3,063 ⟶ 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 3,077 ⟶ 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 3,089 ⟶ 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 3,099 ⟶ 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 3,105 ⟶ 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 3,117 ⟶ 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 3,128 ⟶ 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 3,137 ⟶ 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 3,147 ⟶ 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 3,155 ⟶ 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 3,164 ⟶ 3,727:
 
dofruit;
print "The global fruit is still $fruit";</langsyntaxhighlight>
 
=={{header|Phix}}==
Line 3,193 ⟶ 3,756:
Variables must be declared before use, may be assigned on declaration, and can utilise multiple assignment/sequence decomposition, eg:
 
<!--<langsyntaxhighlight Phixlang="phix">-->
<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>
<!--</langsyntaxhighlight>-->
 
In the latter statement, c is set to "string", b is set to 5, and a is set to {}. (In multiple assignment, values are assigned right-to-left to avoid having to reorder any subscripts.) You could also use
Line 3,207 ⟶ 3,770:
User defined types are declared with a single-parameter function that returns true or false, eg:
 
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">type</span> <span style="color: #000000;">hour</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">>=</span> <span style="color: #000000;">0</span> <span style="color: #008080;">and</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;"><=</span> <span style="color: #000000;">23</span>
Line 3,214 ⟶ 3,777:
<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>
<!--</langsyntaxhighlight>-->
 
Phix has no notion of unsigned numeric types, except via user defined types such as the above which explicitly prevent their use.
Line 3,223 ⟶ 3,786:
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php"><?php
/**
* @author Elad Yosifon
Line 3,385 ⟶ 3,948:
* @url http://php.net/manual/en/resource.php
*/
</syntaxhighlight>
</lang>
 
=={{header|PicoLisp}}==
Line 3,391 ⟶ 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 3,412 ⟶ 3,975:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">/* The PROCEDURE block and BEGIN block are used to delimit scopes. */
 
declare i float; /* external, global variable, excluded from the */
Line 3,433 ⟶ 3,996:
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. */</langsyntaxhighlight>
 
=={{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 3,443 ⟶ 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:
<langsyntaxhighlight lang="powershell">$s = "abc"
$i = 123</langsyntaxhighlight>
Uninitialized variables expand to nothing. This may be interpreted for example as an empty string or 0, depending on context:
<langsyntaxhighlight lang="powershell">4 + $foo # yields 4
"abc" + $foo + "def" # yields "abcdef"</langsyntaxhighlight>
Variables all show up in the '''Variable''': drive and can be queried from there with the usual facilities:
<syntaxhighlight lang ="powershell">Get-ChildItem Variable:</langsyntaxhighlight>
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</langsyntaxhighlight>
as if it were a file or a registry key. There are, however, several cmdlets dealing specifically with variables:
<langsyntaxhighlight 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</langsyntaxhighlight>
 
=={{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 3,541 ⟶ 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|Python}}==
Line 3,548 ⟶ 4,111:
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.
 
<langsyntaxhighlight lang="python">
# these examples, respectively, refer to integer, float, boolean, and string objects
example1 = 3
Line 3,557 ⟶ 4,120:
# example1 now refers to a string object.
example1 = "goodbye"
</syntaxhighlight>
</lang>
 
=={{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 3,573 ⟶ 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 3,587 ⟶ 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 3,595 ⟶ 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 3,647 ⟶ 4,276:
;; racket, structs that are extensions of other structs,
;; pattern-matching on structs, classes, and much more)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 3,657 ⟶ 4,286:
Assigning an array to a scalar variable now makes that scalar variable a reference to the array:
 
<syntaxhighlight lang="raku" line>
<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
Line 3,677 ⟶ 4,306:
say "this is quite bad"; # but then string interpolation
say "this is quite {bad}" # becomes more wordy
</syntaxhighlight>
</lang>
 
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" perl6line>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;</langsyntaxhighlight>
 
{{output}}
Line 3,701 ⟶ 4,330:
=={{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 3,707 ⟶ 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 3,719 ⟶ 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 3,735 ⟶ 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 3,763 ⟶ 4,392:
 
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 3,772 ⟶ 4,401:
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 3,793 ⟶ 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 3,805 ⟶ 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 3,828 ⟶ 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 3,850 ⟶ 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 3,867 ⟶ 4,496:
sand: /*all REXX variables are exposed.*/
q = "Monty" ; say 'sand q=' q /*assign a value ───► "global" Q*/
return</langsyntaxhighlight>
'''output'''
<pre>
Line 3,882 ⟶ 4,511:
===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 3,888 ⟶ 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 3,897 ⟶ 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 3,916 ⟶ 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 3,922 ⟶ 4,551:
a=left(i,2)
Say i var.a.a.4 "(tail is '"a||'.'||a||'.'||'4'"')"
End</langsyntaxhighlight>
Output:
<pre>
Line 3,936 ⟶ 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 3,946 ⟶ 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 3,963 ⟶ 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 3,974 ⟶ 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 3,980 ⟶ 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 3,993 ⟶ 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 4,016 ⟶ 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 4,026 ⟶ 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 4,040 ⟶ 4,718:
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 4,054 ⟶ 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.
<langsyntaxhighlight 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
Line 4,069 ⟶ 4,747:
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>
</lang>
 
=={{header|smart BASIC}}==
Line 4,077 ⟶ 4,755:
 
Numeric variables can contain real and complex numbers.
<langsyntaxhighlight lang="qbasic">x = 14
y = 0.4E3
z = 3-2i</langsyntaxhighlight>
 
String variables use the dollar symbol ($) at the end.
<langsyntaxhighlight lang="qbasic">t$ = "Name"</langsyntaxhighlight>
 
String values may include the quotation symbol " by specifying double quotes "".
<langsyntaxhighlight lang="qbasic">n$ = """This is a quoted text"""</langsyntaxhighlight>
 
===Initialization===
Line 4,093 ⟶ 4,771:
 
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.
<langsyntaxhighlight lang="qbasic">n = 4
a$ = "6 feet"
PRINT n * a$</langsyntaxhighlight>
{{out}}
<pre>
Line 4,107 ⟶ 4,785:
 
Arrays are DIM-ensioned by default with a size of 10. Larger arrays must be pre-DIM-entioned.
<syntaxhighlight lang ="qbasic">DIM name$(100)</langsyntaxhighlight>
 
===Assignment===
Line 4,119 ⟶ 4,797:
===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).
<langsyntaxhighlight lang="qbasic">DEF MyFunction(x)
MyF2 = x^2
MyF3 = x^3
MyFunction = MyF2 + MyF3
END DEF</langsyntaxhighlight>
 
To access the variables within the function:
<langsyntaxhighlight lang="qbasic">x = MyFunction(3)
PRINT x; MyFunction.MyF2; MyFunction.MyF3</langsyntaxhighlight>
 
Variables may also be made global using the DEF command:
<langsyntaxhighlight lang="qbasic">DEF num=123</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
Line 4,136 ⟶ 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.
Line 4,152 ⟶ 4,830:
In SPL variables are autodeclared according to their usage. For example, this one-line program is valid because it is evident what is expected:
 
<langsyntaxhighlight lang="spl">a += 1</langsyntaxhighlight>
 
In contrast, this one-line program raises an error because it is not evident what object "a" is:
 
<langsyntaxhighlight lang="spl">a = a+1</langsyntaxhighlight>
 
'''Assignment.'''
<langsyntaxhighlight lang="spl">a = 1
b,c,d = 0</langsyntaxhighlight>
 
'''Datatypes.'''
Line 4,171 ⟶ 4,849:
An object can become a reference to another object using "~" symbol, for example:
 
<langsyntaxhighlight lang="spl">r = ~a
a = 3
#.output(r)
r = 5
#.output(a)</langsyntaxhighlight>
 
{{out}}
Line 4,190 ⟶ 4,868:
=={{header|SuperCollider}}==
Variables are always local to the scope of a closure or an object.
<syntaxhighlight lang="supercollider">
<lang SuperCollider>
// variable declaration
var table, chair;
Line 4,261 ⟶ 4,939:
~y = { SinOsc.ar(440, 0, 0.1) }; // and a sine tone
 
</syntaxhighlight>
</lang>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">import Foundation
 
// All variables declared outside of a struct/class/etc are global
Line 4,334 ⟶ 5,012:
 
myFunc = showScopes // myFunc is now showScopes
myFunc() // foo bar function</langsyntaxhighlight>
 
=={{header|Tcl}}==
Line 4,340 ⟶ 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 4,362 ⟶ 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 4,371 ⟶ 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 4,379 ⟶ 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 4,395 ⟶ 5,073:
Return x
EndIf
EndFunc</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT,{}
var1=1, var2="b"
Line 4,414 ⟶ 5,092:
PRINT var,"=",@var
ENDLOOP
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,430 ⟶ 5,108:
Simple example: the <code>cases</code>
 
<langsyntaxhighlight lang="txr">@(cases)
hey @a
how are you
Line 4,436 ⟶ 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.
Line 4,451 ⟶ 5,129:
=={{header|uBasic/4tH}}==
uBasic/4tH has two kinds of variables, 26 predefined global integer variables (named <b>A</b> to <b>Z</b>) and a maximum of 26 parameters/local integer variables (named <b>A@</b> to <b>Z@</b>). The latter aren't defined, but merely allocated, using <b>LOCAL(</b><i>n</i><b>)</b> or <b>PARAM(</b><i>n</i><b>)</b>. The first allocated local variable is assigned <b>A@</b>, the second <b>B@</b>, etc. Both parameters and local variables are freed after <b>RETURN</b>. Parameters are always passed by value.
<syntaxhighlight lang="text">' Initialization
A = 15 ' global variable
 
Line 4,470 ⟶ 5,148:
A@ = 5 ' reassignment of parameter A@
B@ = 23 ' local variable
Return</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
Line 4,476 ⟶ 5,154:
{{works with|Bourne Shell}}
 
<syntaxhighlight lang="sh">
<lang sh>
#!/bin/sh
# The unix shell uses typeless variables
Line 4,483 ⟶ 5,161:
pears = `expr 5+4` # We use the external expr to perform the calculation
myfavourite="raspberries"
</syntaxhighlight>
</lang>
 
=={{header|Ursa}}==
<langsyntaxhighlight lang="ursa"># variable declaration
#
# declare [type] [name]
Line 4,528 ⟶ 5,206:
# variables are referenced by their name
decl port p
out p endl console</langsyntaxhighlight>
 
=={{header|VBA}}==
Line 4,614 ⟶ 5,292:
 
<br>'''Variable declaration'''<br>
<langsyntaxhighlight lang="vbnet">Dim variable As datatype
Dim var1,var2,... As datatype</langsyntaxhighlight>
example:
<langsyntaxhighlight lang="vbnet">Dim n1,n2 as Integer
Dim x as Double
Dim isRaining as Boolean
Dim greeting as String</langsyntaxhighlight>
 
<br>'''Initialization'''<br>
<langsyntaxhighlight lang="vbnet">Dim variable As datatype = value
Dim var1,var2,... As datatype</langsyntaxhighlight>
example:
<langsyntaxhighlight 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}}</langsyntaxhighlight>
 
<br>'''Assignment'''<br>
<langsyntaxhighlight lang="vbnet">variable = expression</langsyntaxhighlight>
<langsyntaxhighlight lang="vbnet"> v = a
d = b^2 - 4*a*c
s3 = s1 & mid(s2,3,2)</langsyntaxhighlight>
<langsyntaxhighlight lang="vbnet">variable <operator>= expression2</langsyntaxhighlight>
<langsyntaxhighlight lang="vbnet"> c += a
c -= a
c *= a
Line 4,646 ⟶ 5,324:
c <<= n
c >>= n
c &= a</langsyntaxhighlight>
 
<br>'''Data types'''<br>
Line 4,678 ⟶ 5,356:
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}}==
Line 4,683 ⟶ 5,400:
WDTE does not have variables, per se, but it does have several things that work similarly. The most obvious is function parameters:
 
<langsyntaxhighlight WDTElang="wdte">let example t => io.writeln io.stdout t;</langsyntaxhighlight>
 
The parameters are scoped to the inside of the function in which they're declared. There are also lambdas, which also have parameters:
 
<langsyntaxhighlight WDTElang="wdte">let example t => 3 -> (@ s n => * t n);</langsyntaxhighlight>
 
Lambdas are closures, so they have access to the parameters of the function that called them. The above multiplies 3 by the value of t.
Line 4,693 ⟶ 5,410:
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:
 
<langsyntaxhighlight WDTElang="wdte">let writeToFile name data =>
file.open name : f
-> str.format '{}' data
-> io.writeln f
-- io.close f
;</langsyntaxhighlight>
 
In this example, first <code>file.open name</code> is called. After this, the return value of that call can be accessed later in the chain using <code>f</code>. This is done in the last element as a way of closing the file.
Line 4,704 ⟶ 5,421:
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:
 
<langsyntaxhighlight WDTElang="wdte">let a => 3;
io.writeln io.stdout a;</langsyntaxhighlight>
 
=={{header|Wren}}==
Line 4,717 ⟶ 5,434:
 
Here are a few examples.
<langsyntaxhighlight ecmascriptlang="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'
Line 4,731 ⟶ 5,448:
}
System.print(d) // prints the value of the top level 'd'
System.print(e) // compiler error : Variable is used but not defined</langsyntaxhighlight>
 
=={{header|XPL0}}==
Line 4,766 ⟶ 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 4,784 ⟶ 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 4,796 ⟶ 5,545:
 
=={{header|Zoea}}==
<langsyntaxhighlight Zoealang="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>
</lang>
 
=={{header|Zoea Visual}}==
1,150

edits