Variables
From Rosetta Code
You are encouraged to solve this task according to the task description, using any language you may know.
Demonstrate the language's local variable declaration, initialization, assignment, etc. facilities.
[edit] Ada
declare
X : String := "Hello"; -- Create and initialize a local variable
Y : Integer; -- Create an uninitialized variable
Z : Integer renames Y: -- Rename Y (creates a view)
begin
Y := 1; -- Assign variable
end; -- End of the scope
[edit] 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: <typename> <variablename>;
int j;
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:
LONG REAL double1, double2, double3;
It is possible to initialize variables with expressions having known values when they are defined. The syntax follows the form <typename> <variablename> := <initializing expression>;
SHORT INT b1 := 2500;
LONG INT elwood = 3*bsize, jake = bsize -2;
The strings 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.
FLEX[20]CHAR mystring;
All arrays are structure that include both the lower lwb and upper upb of the array. Hence strings in ALGOL 68 may safely contain null characters 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:
[]CHAR mytext = "The ALGOL 68 Language";
There are more rules regarding arrays, variables containing pointers, dynamic allocation, and initialization that are to extensive to cover here.
[edit] AppleScript
Variables are untyped in AppleScript, but they must be instantiated before use.
Example:set x to 1Scope may be explicitly defined before instantiation using either the
global or local declarations.global xIf 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.
set x to 1
local y
set y to 2
Where a variable has both local and global instances, it is possible to use the my modifier to access the global (top-level) instantiation.
on localx()
set x to 0 -- implicit local
return x
end localx
on globalx()
set x to 0 -- implicit local
return my x
end globalx
on run
set x to 1 -- top-level implicit global
return {localx(), globalx()}
end run
--> RETURNS: {0, 1}
Applescript also supports top-level entities known as properties that are global to that script.
property x : 1Properties 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).
[edit] 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)
Msgbox %x% ; variable dereferencing is done by surrounding '%' signs
fx()
{
local x ; variable default scope in a function is local anyways
global y ;
static z=4 ; initialized once, then value is remembered between function calls
}
[edit] C
Local variables are generally called auto variables in C. Variables must be declared before use. In traditional C, varibles must be declared at the front of a block. The declaration of a variable, without assigning a value takes the form <typename> <variablename>;
int j;
Some common types are: char, short, int, long, float, double and unsigned.
Multiple variables may be defined in a single statement as follows:
double double1, double2, double3;
It is possible to initialize variables with expressions having known values when they are defined. The syntax follows the form <typename> <variablename> = <initializing expression>;
short b1 = 2500;
long elwood = 3*BSIZE, jake = BSIZE -2;
Strings in C are arrays of char terminated by a 0 or NULL character. To declare space for a string of up to 20 characters, the following declaration is used.
char mystring[21];
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:
const char * mytext = "The C Language";
There are more rules regarding arrays, variables containing pointers, dynamic allocation, and initialization that are to extensive to cover here.
[edit] C#
Variables in C# are very dynamic, in the form that they can be declared practically anywhere, with any scope. As in other languages, often used variables are: int, string, double etc.
They are declared with the type first, as in C:
int j;
Multiple variables may be defined in a single line as follows:
int p, a, d;
It is also possible to assign variables, either while declaring or in the program logic:
int a = 4;
int b;
int c = Func(a);
b = 5;
[edit] 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 fallowed by a semicolon ";"
int a;
[edit] E
E is an impure, lexically scoped language. Variables must be defined before use (they are not created on assignment). Definition of variables is a special case of pattern matching.
An identifier occurring in a pattern is a simple non-assignable variable. The def operator is usually used to define local variables:
def x := 1
x + x # returns 2
Assignment
The pattern var x makes x an assignable variable, and := is the assignment operator.
def var x := 1
x := 2
x # returns 2
(As a shorthand, var x := ... is equivalent to def var x := ....)
There are update versions of the assignment operator, in the traditional C style (+=, -=, |=, etc.), but also permitting any verb (method name) to be used:
def var x := 1
x += 1 # equivalent to x := x + 1, or x := x.add(1)
x # returns 2
def var list := ["x"]
list with= "y" # equivalent to list := list.with("y")
list # returns ["x", "y"]
Patterns
Since variable definition is part of pattern matching, a list's elements may be distributed into a set of variables:
def [hair, eyes, var shirt, var pants] := ["black", "brown", "plaid", "jeans"]
However, assignment to a list as in Perl or Python is not currently supported.
[shirt, pants] := ["white", "black"] # This does not do anything useful.
Scoping
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):
def list := [def x := timer.now(), x] # two copies of the current time
list[0] == x # x is still visible here; returns true
Slots
The difference between assignable and non-assignable variables is defined in terms of primitive operations on non-primitive slot objects. Slots can also be employed by programmers for effects such as variables which have an effect when assigned (e.g. backgroundColor := red) 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:
def makeSum() {
var a := 0
var b := 0
return [&a, &b, fn { a + b }]
}
def [&x, &y, sum] := makeSum()
x := 3
y := 4
sum() # returns 7
As suggested by the & 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:
def getUniqueId(&counter) {
counter += 1
return counter
}
var idc := 0
getUniqueId(&idc) # returns 1
getUniqueId(&idc) # returns 2
[edit] 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.
SYMBOL: foo
: use-foo ( -- )
1 foo set
foo get 2 + foo set ! foo now = 3
foo get number>string print ;
:: named-param-example ( a b -- )
a b + number>string print ;
: local-example ( -- str ) [let "a" :> b "c" :> a a " " b 3append ] ;
[edit] Forth
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").
: hypot ( a b -- a^2 + b^2 )
LOCALS| b a | \ note: reverse order from the conventional stack comment
b b * a a * + ;
Works with: GNU Forth Modern Forth implementations often extend this facility in several ways, both for more convenient declaration syntax and to be more compatible with foreign function interfaces. Curly braces are used to replace the conventional stack comment with a similar looking local variable declaration.
: hypot { a b -- a^2 + b^2 } \ text between "--" and "}" remains commentary
a a * b b * + ;
Modern systems may also allow different local data types than just integer cells.
: length { F: a F: b F: c -- len } \ floating point locals
a a F* b b F* F+ c c F* F+ FSQRT ;
[edit] Haskell
You can define a variable at the top (module) level or in a where, let, or do construct.
foobar = 15
f x = x + foobar
where foobar = 15
f x = let foobar = 15
in x + foobar
f x = do
let foobar = 15
return $ x + foobar
One particular feature of do notation looks like assignment, but actually, it's just syntactic sugar for the >>= operator and a unary lambda.
main = do
s <- getLine
print (s, s)
-- The above is equivalent to:
main = getLine >>= \s -> print (s, s)
Pattern matching allows for multiple definitions of the same variable, in which case each call uses the first applicable definition.
funkshun True x = x + 1
funkshun False x = x - 1
foobar = funkshun True 5 + funkshun False 5 -- 6 + 4
case expressions let you do pattern-matching on an arbitrary expression, and hence provide yet another way to define a variable.
funkshun m = case foo m of
[a, b] -> a - b
a : b : c : rest -> a + b - c + sum rest
a -> sum a
Guards are as a kind of syntactic sugar for if-else ladders.
signum x | x > 0 = 1
| x < 0 = -1
| otherwise = 0
A defintion can be accompanied by a type signature, which can request a less general type than the compiler would've chosen on its own. (Because of the monomorphism restriction, there are also some cases where a type signature can request a more general type than the default.) Type signatures are also useful even when they make no changes, as a kind of documentation.
dotProduct :: [Int] -> [Int] -> Int
dotProduct ns ms = sum $ zipWith (+) ns ms
-- Without the type signature, dotProduct would
-- have a more general type.
foobar :: Num a => a
foobar = 15
-- Without the type signature, the monomorphism
-- restriction would cause foobar to have a less
-- general type.
Since Haskell is purely functional, most variables are immutable. It's possible to create mutable variables in an appropriate monad. The exact semantics of such variables largely depend on the monad. For example, STRefs must be explicitly initialized and passed between scopes, whereas the implicit state of a State monad is always accessible via the get function.
[edit] Icon and Unicon
Icon/Unicon data types are implemented as type safe self-descriptive values and as such do not require conventional type declarations. See Introduction to Unicon and Icon about declarations
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.
global gvar # a global
procedure main(arglist) # arglist is a parameter of main
local a,b,i,x # a, b, i, x are locals withing main
static y # a static (silly in main)
x := arglist[1]
a := 1.0
i := 10
b := [x,a,i,b]
# ... rest of program
end
[edit] Icon
[edit] Unicon
This Icon solution works in Unicon.
[edit] J
val=. 0
J has two assignment operators. The =. operator declares, initializes, assigns, etc. a local variable.
It is possible and not uncommon to write an entire J application without using any variables (J has a functional, "point free" style of coding known as tacit).
[edit] Java
Variables in Java are declared before their use with explicit types:
int a;
double b;
AClassNameHere c;
Several variables of the same type can be declared together:
int a, b, c;
Variables can be assigned values on declaration or afterward:
int a = 5;
double b;
int c = 5, d = 6, e, f;
String x = "test";
String y = x;
b = 3.14;
Variables can have scope modifiers, which are explained here.
final variables can only be assigned once, but if they are Objects or arrays, they can be modified through methods (for Objects) or element assignment (for arrays):
final String x = "blah";
final String y;
final double[] nums = new double[15];
y = "test";
x = "blahblah"; //not legal
nums[5] = 2.5; //legal
nums = new double[10]; //not legal
final Date now = new java.util.Date();
now.setTime(1234567890); //legal
now = new Date(1234567890); //not legal
[edit] JavaScript
Information lifted from Stack Overflow (credit to krosenvold and triptych)
Javascript uses scope chains to establish the scope for a given function. There is typically one global scope, and each function defined has its own nested scope. Any function defined within another function has a local scope which is linked to the outer function. It's always the position in the source that defines the scope.
An element in the scope chain is basically a Map with a pointer to it's parent scope.
When resolving a variable, javascript starts at the innermost scope and searches outwards.
// a globally-scoped variable
var a=1;
// global scope
function one(){
alert(a);
}
// local scope
function two(a){
alert(a);
}
// local scope again
function three(){
var a = 3;
alert(a);
}
// Intermediate: no such thing as block scope in javascript
function four(){
if(true){
var a=4;
}
alert(a); // alerts '4', not the global value of '1'
}
// Intermediate: object properties
function Five(){
this.a = 5;
}
// Advanced: closure
var six = function(){
var foo = 6;
return function(){
// javascript "closure" means I have access to foo in here,
// because it is defined in the function in which I was defined.
alert(foo);
}
}()
// Advanced: prototype-based scope resolution
function Seven(){
this.a = 7;
}
// [object].prototype.property loses to [object].property in the scope chain
Seven.prototype.a = -1; // won't get reached, because 'a' is set in the constructor above.
Seven.prototype.b = 8; // Will get reached, even though 'b' is NOT set in the constructor.
// These will print 1-8
one();
two(2);
three();
four();
alert(new Five().a);
six();
alert(new Seven().a);
alert(new Seven().b);
[edit] Joy
JOY does not have variables. Variables essentially name locations in memory, where values are stored. JOY also uses memory to store values, but has no facility to name these locations. The memory that JOY uses is commonly referred to as "the stack".
Initializing
The JOY stack can be initialized:
[] unstack
Assignment
Values can be pushed on the stack:
42
pushes the value 42 of type integer on top of the stack.
Stack
Calling the stack by name pushes a copy of the stack on the stack. To continue the previous example:
stack
pushes the list [42] on top of the stack. The stack now contains: [42] 42.
[edit] 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
make "g1 0
name 2 "g2 ; same as make with parameters reversed
global "g3 ; no initial value
to func :x
make "g4 4 ; still global
localmake "L1 6
local ["L2 "L3] ; local variables, collection syntax
func2 :g4
print :L2 ; 9, modified by func2
print :L3 ; L3 has no value, was not modified by func2
end
to func2 :y
make "g3 :y
make "L2 :L1 + 3 ; dynamic scope: can see variables of callers
localmake "L3 5 ; locally override L3 from caller
(print :y :L1 :L2 :L3) ; 4 6 9 5
end
print :g4 ; 4
print :L1 ; L1 has no value
print name? "L1 ; false, L1 is not bound in the current scope
[edit] LotusScript
Sub Click()
'a few declarations as example
Dim s as New NotesSession ' declaring a New NotesSession actually returns the current, active NotesSession
Dim i as Integer ' i = 0
Dim s as String ' s= ""
Dim v as Variant ' v is nothing
Dim l as Long ' l = 0
Dim doc as NotesDocument 'doc is EMTPY
'...
End Sub
[edit] Modula-3
MODULE Foo EXPORTS Main;
IMPORT IO, Fmt;
VAR foo: INTEGER := 5; (* foo is global (to the module). *)
PROCEDURE Foo() =
VAR bar: INTEGER := 10; (* bar is local to the procedure Foo. *)
BEGIN
IO.Put("foo + bar = " & Fmt.Int(foo + bar) & "\n");
END Foo;
BEGIN
Foo();
END Foo.
For procedures, the formal parameters create local variables unless the actual parameter is prefixed by VAR:
PROCEDURE Foo(n: INTEGER) =
Here, n will be local to the procedure Foo, but if we instead wrote:
PROCEDURE Foo(VAR n: INTEGER) =
Then n is the global variable n (if it exists).
[edit] Objeck
Different ways to declare and initialize an integer.
a : Int;
b : Int := 13;
c := 7;
[edit] OCaml
The default handlers for values in OCaml are not variables strictly speaking, because as OCaml is a functional language these values can't vary (so are not variable). Strictly speaking these are bindings. An identifier is bound to a value in an immutable way.
The standard way to bind an identifier to a value is the let construct:
let x = 28
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:
let y = ref 28
References can then be accessed and modified this way:
!y (* access *)
y := 34 (* modification *)
An identifier can not be declared uninitialised, it is always defined with an initial value, and this initial value is used by the OCaml type inference to infer the type of the binding.
Inside an expression, bindings are defined with the let .. in construct, and we can also define multiple bindings with the let .. and .. in construct (here the expression can be the definition of a new identifier or the definition of a function):
let sum = (* sum is bound to 181 *)
let a = 31
and b = 150 in
(a + b)
let sum () = (* sum is a function which returns 181 *)
let a = 31
and b = 150 in
(a + b)
[edit] Oz
Variable names in Oz always start with an uppercase letter.
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:
declare
Var %% new variable Var, initially free
{Show Var}
Var = 42 %% now Var has the value 42
{Show Var}
Var = 42 %% the same value is assigned again: ok
Var = 43 %% a different value is assigned: exception
In the Emacs-based interactive environment, declare creates a new open scope in which variables can be declared. The variables are visible for the entire rest of the session.
Most operations on free variables block until the variables have been bound (but not Show as used above).
Assignment to dataflow variables is also called unification. It is actually a symmetric operation, e.g. the following binds B to 3:
declare
A = 3
B
in
A = B
{Show B}
However, variables can only be introduced at the left side of the = operator. So this is a syntax error:
declare
A = 3
A = B %% Error: variable B not introduced
in
{Show B}
It is possible to introduce multiple variables in a single statement:
declare
[A B C D] = [1 2 3 4] %% unification of two lists
In a module definition, toplevel variables can be introduced between the keywords define and end without the need for declare. The range between these two keywords is also their scope. Toplevel variables can optionally be exported.
functor
export Function
define
ToplevelVariable = 42
fun {Function}
42
end
end
Function and class definitions introduce a new variable with the name of the function/class and assign the new function/class to this variable.
Most Oz statement introduce a new scope and it is possible to introduce local variables at the top of this scope with the in keyword.
fun {Function Arg}
LocalVar1
in
LocalVar1 = if Arg == 42 then
LocalVar2
in
LocalVar2 = yes
LocalVar2
else
LocalVar3 = no %% variables can be initialized when declared
in
LocalVar3
end
LocalVar1
end
Here, LocalVar1 is visible in the whole body of Function while LocalVar2 is only visible in the then branch and LocalVar3 is only visible in the else branch.
Additionally, new local variables can be introduced everywhere using the keyword local.
if {IsEven 42} then
{System.showInfo "Here, LocalVar is not visible."}
local
LocalVar = "Here, LocalVar IS visible"
in
{System.showInfo LocalVar}
end
end
New variables are also introduced in pattern matching.
case "Rosetta code" of First|_ then {Show First} end %% prints "R"
_ 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 !! 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.
declare
A
B = !!A %% B is a read-only view of A
in
thread
B = 43 %% this blocks until A is known; then it fails because 43 \= 42
end
A = 42
Additional operations on variables:
declare
V = 42
in
{Wait V} %% explicitly wait for V to become determined
if {IsDet V} then %% check whether V is determined; not recommended
{Show determined}
elseif {IsFree V} then %% check whether V is free; not recommended
{Show free}
end
IsFree and IsDet 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:
declare
A = {NewCell 42}
OldVal
in
{Show @A} %% read a cell with @
A := 43 %% change its value
OldVal = A := 44 %% read and write at the same time (atomically)
A is an immutable dataflow variable that is bound to a mutable reference.
[edit] Perl
Variables can be declared with our, my, or local, or they can be used without being declared at all; see scope modifiers for the differences. In any case, variables which haven't been assigned to have the undefined value by default. The undefined value acts just like 0 (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 defined function. Also, 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.
Initialization and assignment are the same thing in Perl: just use the = operator. Note that the rvalue's context (scalar or list) is determined based on the lvalue.
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
# element of @a.
my @b = @a; # List assignment; @b becomes the same length
# as @a and each element becomes the same.
my ($x, $y, @b) = @a; # List assignment; $x and $y get the first
# two elements of @a, and @b the rest.
my ($x, $y, @b, @c, $z) = @a; # Same thing, and also @c becomes empty
# and $z undefined.
The kind of value a variable can hold depends on its sigil, "sigil" being a slang term for "funny character in front of a variable name". $dollarsigns can hold scalars: the undefined value, numbers, strings, or references. @atsigns can hold arrays of scalars, and %percentsigns 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.
There are two other sigils, but they behave quite unlike the others. A token of the form &foo refers to a subroutine named foo. In older versions of Perl, ampersands were necessary for calling user-defined subroutines, but since they no longer are, they have only a handful of obscure uses, like making references to named subroutines. Note that you can't assign to an ampersand-marked name. But you can assign to a typeglob, a kind of object represented with the notation *var. A typeglob *foo represents the symbol-table entry for all of the otherwise independent variables $foo, @foo, %foo, and &foo. Assigning a string "bar" to *foo makes these variables aliases for $bar, @bar, %bar, and &bar respectively. Alternatively, you can assign a reference to a typeglob, which creates an alias only for the variable of the appropriate type. In particular, you can say *twiddle = sub {...} to change the definition of the subroutine &twiddle without affecting $twiddle and friends.
[edit] PL/I
/* The PROCEDURE block and BEGIN block are used to delimit scopes. */
declare i float; /* external, global variable, excluded from the */
/* local ares (BEGIN block) below. */
begin;
declare (i, j) fixed binary; /* local variable */
get list (i, j);
put list (i,j);
end;
/* Examples of initialization. */
declare p fixed initial (25);
declare q(7) fixed initial (9, 3, 5, 1, 2, 8, 15);
/* sets all elements of array Q at run time, on block entry. */
declare r(7) fixed initial (9, 3, 5, 1, 2, 8, 15);
/* sets all elements of array R at compile time. */
p = 44; /* run-time assignment. */
q = 0; /* run-time initialization of all elements of Q to zero. */
q = r; /* run-time assignment of all elements of array R to */
/* corresponding elemets of S. */
[edit] PicoLisp
You can control the local bindings of symbols with functions like 'use' or 'let':
(use (A B C)
(setq A 1 B 2 C 3)
... )
This is equivalent to
(let (A 1 B 2 C 3)
... )
The parentheses can be omitted if there is only a single variable
(use A
(setq A ..)
... )
(let A 1
...)
Other functions that handle local bindings are 'let?', 'bind', 'job', 'with' or 'for'.
[edit] 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
Debug b$
; This initializes a double precision float, if type is following the dot
Debug c.d
; They can be initialized with define (double precision float, string, integer)
Define d.d = 3.5, e$ = "Test", f.i = a + 2
; Define can have a default type (all bytes except j which is long):
Define.b g, h, j.l
; Define without following variables sets default type. In this case to single precision float
Define.f
; So this will be an single precision float and no integer
Debug k
; EnableExplicit forces declaration of used variables with define
EnableExplicit
; Will throw an error because L isn't initialized
Debug L
DisableExplicit
; Global Variables are available in Procedures and Threads too
Global M = 3, N = 2
Procedure Dummy(parameter1, parameter2 = 20)
; Parameter contain values which where used when calling the function,
; their types have to be specified in the above Procedure header.
; The last ones can have default values which get applied if this parameter is not given.
; Variables in Procedures are separate from those outside,
; so d can be initialized again with another type
; which would otherwise lead to an error
d.i
; Protected makes a variable local even if another one with same name is declared as global (see above)
Protected M = 2
; Shares a variable with main program like it was declared by global
Shared a
; prevents a variable to be initialized with default value again when procedure is called a second time,
; could be used for example as a counter, which contains the number of times a function was called
Static a
; N here also would have a value of 2, while for example
; f would, when named, initialize a new variable, and so have a value of 0
EndProcedure
; finally there are constants which are prefixed by an #:
#Test = 1
; Their value cannot be changed while program is running
#String_Constant = "blubb"
; 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
[edit] PowerShell
Variables in PowerShell start with a $ character, they are created on assignment and thus don't need to be declared:
$s = "abc"
$i = 123
Uninitialized variables expand to nothing. This may be interpreted for example as an empty string or 0, depending on context:
4 + $foo # yields 4
"abc" + $foo + "def" # yields "abcdef"
Variables all show up in the Variable: drive and can be queried from there with the usual facilities:
Get-ChildItem Variable:
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
Remove-Item Variable:foo
as if it were a file or a registry key. There are, however, several cmdlets dealing specifically with variables:
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
[edit] Python
Names in Python are not typed, although all the objects referred to by them, are. Names are lexically scoped by function/method/class definitions, and must be defined before use.
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.
[edit] 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.
foo <- 3.4
bar = "abc"
It is possible to assign multiple variables with the same value, and to assign values from left to right.
baz <- quux <- 1:10
TRUE -> quuux
There are also global assignment operators, <<- and ->>. From their help page:
The operators '<<-' and '->>' cause a search to made through the environment for an existing definition of the variable being assigned. If such a variable is found (and its binding is not locked) then its value is redefined, otherwise assignment takes place in the global environment.
In practice, this usually means that variables are assigned in the user workspace (global environment) rather than a function.
a <- 3
assignmentdemo <- function()
{
message("assign 'a' locally, i.e. within the scope of the function")
a <- 5
message(paste("inside assignmentdemo, a = ", a))
message(paste("in the global environment, a = ", get("a", envir=globalenv())))
message("assign 'a' globally")
a <<- 7
message(paste("inside assignmentdemo, a = ", a))
message(paste("in the global environment, a = ", get("a", envir=globalenv())))
}
assignmentdemo()
assign 'a' locally, i.e. within the scope of the function inside assignmentdemo, a = 5 in the global environment, a = 3 assign 'a' globally inside assignmentdemo, a = 5 in the global environment, a = 7
Finally, there is also the assign function, where you choose the environment to assign the variable.
assign("b", TRUE) #equivalent to b <- TRUE
assign("c", runif(10), envir=globalenv()) #equivalent to c <<- runif(10)
[edit] Ruby
Information taken from Variables page at the Ruby User's Guide
Ruby has three kinds of variables, one kind of constant and exactly two pseudo-variables. The variables and the constants have no type. While untyped variables have some drawbacks, they have many more advantages and fit well with ruby's quick and easy philosophy. Variables must be declared in most languages in order to specify their type, modifiability (i.e., whether they are constants), and scope; since type is not an issue, and the rest is evident from the variable name as you are about to see, we do not need variable declarations in ruby. The first character of an identifier categorizes it at a glance:
$ global variable @ instance variable [a-z] or _ local variable [A-Z] constant The only exceptions to the above are ruby's pseudo-variables:
self, which always refers to the currently executing object, andnil, which is the meaningless value assigned to uninitialized variables. Both are named as if they are local variables, butselfis a global variable maintained by the interpreter, andnilis really a constant. As these are the only two exceptions, they don't confuse things too much.
Referencing an undefined global or instance variable returns nil. Referencing an undefined local variable throws a NameError exception.
$a_global_var = 5
class Demo
@@a_class_var = 6
A_CONSTANT = 8
def initialize
@an_instance_var = 7
end
def incr(a_local_var)
@an_instance_var += a_local_var
end
end
[edit] SNOBOL4
Local variables in Snobol are declared in a function definition prototype string:
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
This defines a function foo( ) taking two arguments x,y and three localized variables a,b,c. Both the argument parameters and vars are dynamically scoped to the function body, and visible to any called functions within that scope. The function name also behaves as a local variable, and may be assigned to as the return value of the function. Any variable initialization or assignment is done explicitly within the function body. Unassigned variables have a null string value, which behaves as zero in numeric context.
Snobol does not support static or lexical scoping, or module level namespaces. Any variables not defined in a prototype are global to the program.
[edit] Tcl
Tcl's variables are local to procedures, lambdas and methods by default, and there is no initialization per se: only assignment when the variable previously did not exist.
Demonstrating:
namespace eval foo {
# Define a procedure with two formal arguments; they are local variables
proc bar {callerVarName argumentVar} {
### Associate some non-local variables with the procedure
global globalVar; # Variable in global namespace
variable namespaceVar; # Variable in local (::foo) namespace
# Access to variable in caller's context; may be local or global
upvar 1 callerVarName callerVar
### Reading a variable uses the same syntax in all cases
puts "caller's var has $callerVar"
# But global and namespace vars can be accessed by using qualified names
puts "global var has $globalVar which is $::globalVar"
### Writing a variable has no special syntax
### but [set] is by far the most common command for writing
set namespaceVar $globalVar
incr globalVar
### Destroying a variable is done like this
unset argumentVar
}
}
The main thing to note about Tcl is that the "$" syntax is a language level operator for reading a variable and not just general syntax for referring to a variable.
[edit] TI-83 BASIC
Variables will remain global, even after the program is complete. Global variables persist until deleted (or reset or power loss, unless they are archived).
Variables may be assigned with the → to a value.
:1→A
[edit] TI-89 BASIC
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).
Local mynum, myfunc
Variables may be assigned with the → or Define statements, both of which assign a new value to a variable. → is typically used interactively, but only Define can assign programs or multi-statement functions.
Define mynum = 1 © Two ways to assign a number
1 → mynum
Define myfunc(x) = (sin(x))^2 © Two ways to assign a function
(sin(x))^2 → myfunc(x)
Define myfunc(x) = Func © Multi-statement function
If x < 0 Then
Return –x
Else
Return x
EndIf
EndFunc
[edit] XSLT
Although called variables, XSLT "variable" elements are single-assignment, and so behave more like constants. They are valid in the node scope in which they are declared.
<xsl:variable name="foo" select="XPath expression" />
<xsl:if test="$foo = 4">... </xsl:if> <!-- prepend '$' to reference a variable or parameter-->

