Comparison of programming languages (basic instructions)

From testwiki
Jump to navigation Jump to search

Template:Short description Template:Refimprove Template:ProgLangCompare This article compares a large number of programming languages by tabulating their data types, their expression, statement, and declaration syntax, and some common operating-system interfaces.

Conventions of this article

Generally, var, Template:Var, or Template:Var serif is how variable names or other non-literal values to be interpreted by the reader are represented. The rest is literal code. Guillemets (Template:Code and Template:Code) enclose optional sections. Template:Keypress indicates a necessary (whitespace) indentation.

The tables are not sorted lexicographically ascending by programming language name by default, and that some languages have entries in some tables but not others. Template:Clear

Type identifiers

8 bit (byte) 16 bit (short integer) 32 bit 64 bit (long integer) Word size Arbitrarily precise (bignum)
Signed Unsigned Signed Unsigned Signed Unsigned Signed Unsigned Signed Unsigned
Ada[1] range -2**7 .. 2**7 - 1Template:Ref range 0 .. 2**8 - 1Template:Ref or mod 2**8Template:Ref range -2**15 .. 2**15 - 1Template:Ref range 0 .. 2**16 - 1Template:Ref or mod 2**16Template:Ref range -2**31 .. 2**31 - 1Template:Ref range 0 .. 2**32 - 1Template:Ref or mod 2**32Template:Ref range -2**63 .. 2**63 - 1Template:Ref mod 2**64Template:Ref IntegerTemplate:Ref range 0 .. 2**Integer'Size - 1Template:Ref or mod Integer'SizeTemplate:Ref Template:N/a
ALGOL 68 (variable-width) short short intTemplate:Ref rowspan=2 Template:N/a short intTemplate:Ref rowspan=2 Template:N/a intTemplate:Ref rowspan=2 Template:N/a long intTemplate:Ref rowspan=2 Template:N/a intTemplate:Ref Template:N/a long long intTemplate:RefTemplate:Ref
bytes and bits
C (C99 fixed-width) int8_t uint8_t int16_t uint16_t int32_t uint32_t int64_t uint64_t intptr_tTemplate:Ref size_tTemplate:Ref rowspan=5 Template:N/a
C++ (C++11 fixed-width)
C (C99 variable-width) signed char unsigned char shortTemplate:Ref unsigned shortTemplate:Ref longTemplate:Ref unsigned longTemplate:Ref long longTemplate:Ref unsigned long longTemplate:Ref intTemplate:Ref unsigned intTemplate:Ref
C++ (C++11 variable-width)
Objective-C (Cocoa) signed char or int8_t unsigned char or uint8_t short or int16_t unsigned short or uint16_t int or int32_t unsigned int or uint32_t long long or int64_t unsigned long long or uint64_t NSInteger or long NSUInteger or unsigned long
C# sbyte byte short ushort int uint long ulong IntPtr UIntPtr System.Numerics.BigInteger
(.NET 4.0)
Java byte Template:N/a charTemplate:Ref Template:N/a Template:N/a Template:N/a Template:N/a java.math.BigInteger
Go int8 uint8 or byte int16 uint16 int32 uint32 int64 uint64 int uint big.Int
Rust i8 u8 i16 u16 i32 u32 i64 u64 isize usize Template:N/a
Swift Int8 UInt8 Int16 UInt16 Int32 UInt32 Int64 UInt64 Int UInt
D byte ubyte short ushort int uint long ulong Template:N/a Template:N/a BigInt
Common Lisp[2] (signed-byte 8) (unsigned-byte 8) (signed-byte 16) (unsigned-byte 16) (signed-byte 32) (unsigned-byte 32) (signed-byte 64) (unsigned-byte 64) bignum
Scheme
ISLISP[3] bignum
Pascal (FPC) shortint byte smallint word longint longword int64 qword integer cardinal Template:N/a
Visual Basic Template:N/a Byte Integer Template:N/a Long Template:N/a colspan=2 Template:N/a rowspan=2 colspan=2 Template:N/a rowspan=1 Template:N/a
Visual Basic .NET SByte Short UShort Integer UInteger Long ULong System.Numerics.BigInteger
(.NET 4.0)
FreeBasic Byte or Integer<8> UByte or UInteger<8> Short or Integer<16> UShort or UInteger<16> Long or Integer<32> ULong or UInteger<32> LongInt or Integer<64> ULongInt or UInteger<64> Integer UInteger Template:N/a
Python 2.x colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a int Template:N/a long
Python 3.x colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a int
S-Lang colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a Template:N/a
Fortran INTEGER(KIND = n)Template:Ref Template:N/a INTEGER(KIND = n)Template:Ref Template:N/a INTEGER(KIND = n)Template:Ref Template:N/a INTEGER(KIND = n)Template:Ref Template:N/a
PHP colspan=2 Template:N/a colspan=2 Template:N/a intTemplate:Ref Template:N/a intTemplate:Ref Template:N/a colspan=2 Template:N/a Template:Ref
Perl 5 colspan=2 Template:N/aTemplate:Ref colspan=2 Template:N/aTemplate:Ref colspan=2 Template:N/aTemplate:Ref colspan=2 Template:N/aTemplate:Ref colspan=2 Template:N/aTemplate:Ref Math::BigInt
Raku int8 uint8 int16 uint16 int32 uint32 int64 uint64 Int colspan=2 Template:N/a
Ruby colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a Fixnum Template:N/a Bignum
ErlangTemplate:Ref colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a integer() Template:N/a integer()Template:Ref
Scala Byte Template:N/a Short CharTemplate:Ref Int Template:N/a Long Template:N/a Template:N/a Template:N/a scala.math.BigInt
Seed7 Template:N/a Template:N/a Template:N/a Template:N/a Template:N/a Template:N/a integer Template:N/a Template:N/a Template:N/a bigInteger
Smalltalk colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a SmallIntegerTemplate:Ref Template:N/a LargeIntegerTemplate:Ref
Windows PowerShell colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a Template:N/a
OCaml colspan=2 Template:N/a colspan=2 Template:N/a int32 Template:N/a int64 Template:N/a int or nativeint open Big_int;; or big_int
F# sbyte byte int16 uint16 int32 or int uint32 uint64 nativeint unativeint bigint
Standard ML Template:N/a Word8.word colspan=2 Template:N/a Int32.int Word32.word Int64.int Word64.word int word LargeInt.int or
IntInf.int
Haskell (GHC) «import Int» or Int8 «import Word» or Word8 «import Int» or Int16 «import Word» or Word16 «import Int» or Int32 «import Word» or Word32 «import Int» or Int64 «import Word» or Word64 Int «import Word» or Word Integer
Eiffel INTEGER_8 NATURAL_8 INTEGER_16 NATURAL_16 INTEGER_32 NATURAL_32 INTEGER_64 NATURAL_64 INTEGER NATURAL Template:N/a
COBOLTemplate:Ref BINARY-CHAR «SIGNED» BINARY-CHAR UNSIGNED BINARY-SHORT «SIGNED» BINARY-SHORT UNSIGNED BINARY-LONG «SIGNED» BINARY-LONG UNSIGNED BINARY-DOUBLE «SIGNED» BINARY-DOUBLE UNSIGNED Template:N/a Template:N/a Template:N/a
Mathematica colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a Integer
Wolfram Language colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a colspan=2 Template:N/a Integer
  • Template:Note The standard constants int shorts and int lengths can be used to determine how many shorts and longs can be usefully prefixed to short int and long int. The actual sizes of short int, int, and long int are available as the constants short max int, max int, and long max int etc.
  • Template:Note Commonly used for characters.
  • Template:Note The ALGOL 68, C and C++ languages do not specify the exact width of the integer types short, int, long, and (C99, C++11) long long, so they are implementation-dependent. In C and C++ short, long, and long long types are required to be at least 16, 32, and 64 bits wide, respectively, but can be more. The int type is required to be at least as wide as short and at most as wide as long, and is typically the width of the word size on the processor of the machine (i.e. on a 32-bit machine it is often 32 bits wide; on 64-bit machines it is sometimes 64 bits wide). C99 and C++11Template:Citation needed also define the [u]intN_t exact-width types in the stdint.h header. See C syntax#Integral types for more information. In addition the types size_t and ptrdiff_t are defined in relation to the address size to hold unsigned and signed integers sufficiently large to handle array indices and the difference between pointers.
  • Template:Note Perl 5 does not have distinct types. Integers, floating point numbers, strings, etc. are all considered "scalars".
  • Template:Note PHP has two arbitrary-precision libraries. The BCMath library just uses strings as datatype. The GMP library uses an internal "resource" type.
  • Template:Note The value of n is provided by the SELECTED_INT_KIND[4] intrinsic function.
  • Template:Note ALGOL 68G's runtime option --precision "number" can set precision for long long ints to the required "number" significant digits. The standard constants long long int width and long long max int can be used to determine actual precision.
  • Template:Note COBOL allows the specification of a required precision and will automatically select an available type capable of representing the specified precision. "PIC S9999", for example, would require a signed variable of four decimal digits precision. If specified as a binary field, this would select a 16-bit signed type on most platforms.
  • Template:Note Smalltalk automatically chooses an appropriate representation for integral numbers. Typically, two representations are present, one for integers fitting the native word size minus any tag bit (Template:Mono) and one supporting arbitrary sized integers (Template:Mono). Arithmetic operations support polymorphic arguments and return the result in the most appropriate compact representation.
  • Template:Note Ada range types are checked for boundary violations at run-time (as well as at compile-time for static expressions). Run-time boundary violations raise a "constraint error" exception. Ranges are not restricted to powers of two. Commonly predefined Integer subtypes are: Positive (range 1 .. Integer'Last) and Natural (range 0 .. Integer'Last). Short_Short_Integer (8 bits), Short_Integer (16 bits) and Long_Integer (64 bits) are also commonly predefined, but not required by the Ada standard. Runtime checks can be disabled if performance is more important than integrity checks.
  • Template:Note Ada modulo types implement modulo arithmetic in all operations, i.e. no range violations are possible. Modulos are not restricted to powers of two.
  • Template:Note Commonly used for characters like Java's char.
  • Template:Note int in PHP has the same width as long type in C has on that system.Template:Ref
  • Template:Note Erlang is dynamically typed. The type identifiers are usually used to specify types of record fields and the argument and return types of functions.[5]
  • Template:Note When it exceeds one word.[6]
Single precision Double precision Other precision Processor dependent
Ada[1] Float Long_Float Template:N/a
ALGOL 68 realTemplate:Ref long realTemplate:Ref short real, long long real, etc.Template:Ref
C floatTemplate:Ref double long doubleTemplate:Ref
C++ (STL)
Objective-C (Cocoa) CGFloat
C# float rowspan=4 Template:N/a
Java
Go float32 float64
Rust f32 f64
Swift Float or Float32 Double or Float64 Float80Template:Ref CGFloat
D float double real
Common Lisp single-float double-float float, short-float, long-float
Scheme
ISLISP
Pascal (FPC) single double real
Visual Basic Single Double rowspan=3 Template:N/a
Visual Basic .NET
Xojo
Python rowspan=2 Template:N/a float
JavaScript Number[7] Template:N/a
S-Lang
Fortran REAL(KIND = n)Template:Ref
PHP float
Perl
Raku num32 num64 Num
Ruby Template:N/a Float rowspan=4 Template:N/a
Scala Float Double
Seed7 Template:N/a float
Smalltalk Float Double
Windows PowerShell
OCaml Template:N/a float rowspan=3 Template:N/a
F# float32
Standard ML Template:N/a real
Haskell (GHC) Float Double
Eiffel REAL_32 REAL_64
COBOL FLOAT-BINARY-7Template:Ref FLOAT-BINARY-34Template:Ref FLOAT-SHORT, FLOAT-LONG, FLOAT-EXTENDED
Mathematica Template:N/a Template:N/a Real
  • Template:Note The standard constants real shorts and real lengths can be used to determine how many shorts and longs can be usefully prefixed to short real and long real. The actual sizes of short real, real, and long real are available as the constants short max real, max real and long max real etc. With the constants short small real, small real and long small real available for each type's machine epsilon.
  • Template:Note declarations of single precision often are not honored
  • Template:Note The value of n is provided by the SELECTED_REAL_KIND[8] intrinsic function.
  • Template:Note ALGOL 68G's runtime option --precision "number" can set precision for long long reals to the required "number" significant digits. The standard constants long long real width and long long max real can be used to determine actual precision.
  • Template:Note These IEEE floating-point types will be introduced in the next COBOL standard.
  • Template:Note Same size as double on many implementations.
  • Template:Note Swift supports 80-bit extended precision floating point type, equivalent to long double in C languages.
Integer Single precision Double precision Half and Quadruple precision etc.
Ada[1] Template:N/a ComplexTemplate:Ref ComplexTemplate:Ref ComplexTemplate:Ref
ALGOL 68 Template:N/a compl long compl etc. short compl etc. and long long compl etc.
C (C99)[9] Template:N/a float complex double complex rowspan=7 Template:N/a
C++ (STL) Template:N/a std::complex<float> std::complex<double>
C# Template:N/a Template:N/a System.Numerics.Complex
(.NET 4.0)
Java Template:N/a Template:N/a Template:N/a
Go Template:N/a complex64 complex128
D Template:N/a cfloat cdouble
Objective-C Template:N/a Template:N/a Template:N/a
Common Lisp (complex integer) (complex single-float) (complex double-float) complex
Scheme rowspan=4 Template:N/a
Pascal Template:N/a Template:N/a
Visual Basic Template:N/a Template:N/a
Visual Basic .NET Template:N/a Template:N/a System.Numerics.Complex
(.NET 4.0)
Perl Math::Complex
Raku complex64 complex128 Complex
Python complex rowspan=15 Template:N/a
JavaScript Template:N/a Template:N/a
S-Lang Template:N/a Template:N/a
Fortran COMPLEX(KIND = n)Template:Ref
Ruby Complex Template:N/a Complex
Scala Template:N/a Template:N/a Template:N/a
Seed7 Template:N/a Template:N/a complex
Smalltalk Complex Complex Complex
Windows PowerShell Template:N/a Template:N/a
OCaml Template:N/a Template:N/a Complex.t
F# System.Numerics.Complex
(.NET 4.0)
Standard ML Template:N/a Template:N/a Template:N/a
Haskell (GHC) Template:N/a ComplexTemplate:Not a typoComplex Float ComplexTemplate:Not a typoComplex Double
Eiffel Template:N/a Template:N/a Template:N/a
COBOL Template:N/a Template:N/a Template:N/a
Mathematica Complex Template:N/a Template:N/a Complex
  • Template:Note The value of n is provided by the SELECTED_REAL_KIND[8] intrinsic function.
  • Template:Note Generic type which can be instantiated with any base floating point type.

Other variable types

Text Boolean Enumeration Object/Universal
Character StringTemplate:Ref
Ada[1] Character String, Bounded_String, Unbounded_String Boolean (item1, item2, ...) tagged null record
ALGOL 68 char string, bytes bool, bits Template:N/a - User defined Template:N/a
C (C99) char, wchar_t Template:N/a boolTemplate:Ref enum «name» { item1, item2, ... }; void *
C++ (STL) «std::»string
Objective-C unichar NSString * BOOL id
C# char string bool enum name { item1« = value», item2« = value», ... } object
Java String boolean enum name { item1, item2, ... } Object
Go byte, rune string bool const (
Template:SpacesitemTemplate:Sub = iota
Template:SpacesitemTemplate:Sub
Template:Spaces...
)
interface{}
Rust char String bool enum name { itemTemplate:Sub« = value», itemTemplate:Sub« = value», ... } std::any::Any
Swift Character String Bool enum name { case item1, item2, ... } Any
D char string bool enum name { item1, item2, ... } std.variant.Variant
Common Lisp character string boolean (member item1 item2 ...) t
Scheme
ISLISP
Pascal (ISO) char Template:N/a boolean ( item1, item2, ... ) Template:N/a
Object Pascal (Delphi) string variant
Visual Basic Template:N/a String Boolean Enum name
Template:SpacesitemTemplate:Sub «= value»
Template:SpacesitemTemplate:Sub «= value»
Template:Spaces...

End Enum
[[Variant type|Variant]]
Visual Basic .NET Char Object
Xojo Template:N/a Object or Variant
Python Template:N/aTemplate:Ref str bool from enum import Enum
class Name(Enum):
Template:SpacesitemTemplate:Sub = value
Template:SpacesitemTemplate:Sub = value
Template:Spaces...
object
JavaScript Template:N/aTemplate:Ref String Boolean Object
S-Lang
Fortran CHARACTER(LEN = *) CHARACTER(LEN = :), allocatable LOGICAL(KIND = n)Template:Ref CLASS(*)
PHP Template:N/aTemplate:Ref string bool (type declaration omitted)
Perl Template:N/aTemplate:Ref UNIVERSAL
Raku Char Str Bool enum name<item1 item2 ...>
enum name <<:item1(value) :item2(value) ..>>
Mu
Ruby Template:N/aTemplate:Ref String ObjectTemplate:Ref Object
Scala Char String Boolean object name extends Enumeration {
Template:Spacesval itemTemplate:Sub, itemTemplate:Sub, ... = Value
}
Any
Seed7 char string boolean const type: name is new enum
Template:SpacesitemTemplate:Sub,
Template:SpacesitemTemplate:Sub,
Template:Spaces...
end enum;
Windows PowerShell
OCaml char string bool Template:N/aTemplate:Ref Template:N/a
F# type name = item1 = value Template:Pipeitem2 = value Template:Pipe ... obj
Standard ML Template:N/aTemplate:Ref Template:N/a
Haskell (GHC) Char String Bool Template:N/aTemplate:Ref Template:N/a
Eiffel CHARACTER STRING BOOLEAN Template:N/a ANY
COBOL PIC X PIC X(string length) or PIC X«X...» PIC 1«(number of digits or PIC 1«1...» Template:N/a OBJECT REFERENCE
Mathematica Template:N/aTemplate:Ref String Template:N/a
  • Template:Note specifically, strings of arbitrary length and automatically managed.
  • Template:Note This language represents a boolean as an integer where false is represented as a value of zero and true by a non-zero value.
  • Template:Note All values evaluate to either true or false. Everything in TrueClass evaluates to true and everything in FalseClass evaluates to false.
  • Template:NoteThis language does not have a separate character type. Characters are represented as strings of length 1.
  • Template:Note Enumerations in this language are algebraic types with only nullary constructors
  • Template:Note The value of n is provided by the SELECTED_INT_KIND[4] intrinsic function.

Derived types

Template:Further

fixed size array dynamic size array
one-dimensional array multidimensional array one-dimensional array multidimensional array
Ada[1] array (<first> .. <last>) of <type>
or
array (<discrete_type>) of <type>
array (<first1> .. <last1>, <first2> .. <last2>, ...) of <type>
or
array (<discrete_type1>, <discrete_type2>, ...) of <type>
array (<discrete_type> range <>) of <type> array (<discrete_type1> range <>, <discrete_type2> range <>, ...) of <type>
ALGOL 68 [first:last]«modename»
or simply:
[size]«modename»
[first1:last1, first2:last2]«modename»
or
[first1:last1][first2:last2]«modename»
etc.
flex[first:last]«modename»
or simply:
flex[size]«modename»
flex[first1:last1, first2:last2]«modename»
or
flex[first1:last1]flex[first2:last2]«modename» etc.
C (C99) type name[size]Template:Ref type name[size1][size2]Template:Ref type *name
or within a block:
int n = ...; type name[n]
C++ (STL) «std::»array<type, size>(C++11) «std::»vector<type>
C# type[] type[[[:Template:Not a typo]]...] System.Collections.ArrayList
or
System.Collections.Generic.List<type>
Java type[]Template:Ref type[][]...Template:Ref ArrayList or ArrayList<type>
D type[size] type[size1][size2] type[]
Go [size]type [size1][size2]...type []type [][]type
Rust [type; size] [[type; size1]; size2] Vec<type> Vec<Vec<type>>
Swift [type] or Array<type> [[type]] or Array<Array<type>>
Objective-C NSArray NSMutableArray
JavaScript Template:N/a Template:N/a ArrayTemplate:Ref
Common Lisp (simple-array type (dimension)) (simple-array type (dimension1 dimension2)) (array type (dimension)) (array type (dimension1 dimension2))
Scheme
ISLISP
Pascal array[first..last] of typeTemplate:Ref array[first1..last1] of array[first2..last2] ... of typeTemplate:Ref
or
array[first1..last1, first2..last2, ...] of typeTemplate:Ref
Template:N/a Template:N/a
Object Pascal (Delphi) array of type array of array ... of type
Visual Basic Dim x(last) As type Dim x(last1, last2,...) As type
Visual Basic .NET type() type(Template:Not a typo...) System.Collections.ArrayList
or
System.Collections.Generic.List(Of type)
Python list
S-Lang x = type[size]; x = type[size1, size2, ...];
Fortran type :: name(size) type :: name(size1, size2,...) type, ALLOCATABLE :: name(:) type, ALLOCATABLE :: name(:,:,...)
PHP array
Perl
Raku Array[type] or Array of type
Ruby x = Array.new(size1){ Array.new(size2) } Array
Scala Array[type] Array[...[Array[type]]...] ArrayBuffer[type]
Seed7 array type
or
array [idxType] type
array array type
or
array [idxType] array [idxType] type
array type
or
array [idxType] type
array array type
or
array [idxType] array [idxType] type
Smalltalk Array OrderedCollection
Windows PowerShell type[] type[[[:Template:Not a typo]]...]
OCaml type array type array ... array
F# type []
or
type array
type [[[:Template:Not a typo]]...] System.Collections.ArrayList
or
System.Collections.Generic.List<type>
Standard ML type vector or type array
Haskell (GHC) x = Array.array (0, size-1) list_of_association_pairs x = Array.array ((0, 0,...), (size1-1, size2-1,...)) list_of_association_pairs
COBOL level-number type OCCURS size «TIMES». Template:Em level-number type OCCURS min-size TO max-size «TIMES» DEPENDING «ON» size.Template:Ref Template:N/a
  • Template:NoteIn most expressions (except the sizeof and & operators), values of array types in C are automatically converted to a pointer of its first argument. See C syntax#Arrays for further details of syntax and pointer operations.
  • Template:Note The C-like type x[] works in Java, however type[] x is the preferred form of array declaration.
  • Template:Note Subranges are used to define the bounds of the array.
  • Template:Note JavaScript's array are a special kind of object.
  • Template:Note The DEPENDING ON clause in COBOL does not create a true variable length array and will always allocate the maximum size of the array.

Other types

Simple composite types Algebraic data types Unions
Records Tuple expression
Ada[1] type name is «abstract» «tagged» «limited» [recordTemplate:IndentfieldTemplate:Sub : type;Template:IndentfieldTemplate:Sub : type;Template:Indent...
end record Template:Pipe null record]
Template:N/a Any combination of records, unions, and enumerations (as well as references to those, enabling recursive types). type name (variation : discrete_type) is recordTemplate:Indentcase variation isTemplate:Indentwhen choice_listTemplate:Sub =>Template:IndentfieldnameTemplate:Sub : type;Template:Indent...Template:Indentwhen choice_listTemplate:Sub =>Template:IndentfieldnameTemplate:Sub : type;Template:Indent...Template:Indent...Template:Indentend case;
end record
ALGOL 68 struct (modename «fieldname», ...); Required types and operators can be user-defined union (modename, ...);
C (C99) struct «name» {type name;...}; rowspan=2 Template:N/a rowspan=3 Template:N/a union {type name;...};
Objective-C
C++ struct «name» {type name;...};Template:Ref «std::»tuple<typeTemplate:Sub..typeTemplate:Sub>
C# struct name {type name;...} (valTemplate:Sub, valTemplate:Sub, ... ) rowspan=3 Template:N/a
Java Template:N/aTemplate:Ref
JavaScript Template:N/a
D struct name {type name;...} std.variant.Algebraic!(type,...) union {type name;...}
Go struct { Template:Indent«name» typeTemplate:Indent...
}
Rust struct name {name: type, ...} (valTemplate:Sub, valTemplate:Sub, ... ) enum name { Foo(types), ...} union name {name: type, ...}
Swift struct name {Template:Indentvar name «: type»Template:Indent...
}
(«nameTemplate:Sub:» valTemplate:Sub, «nameTemplate:Sub:» valTemplate:Sub, «nameTemplate:Sub:» valTemplate:Sub, ... ) enum name { case Foo«(types)» case Bar «(types... }
Common Lisp (defstruct name slot-name (slot-name initial-value) (slot-name initial-value :type type) ...) (cons valTemplate:Sub valTemplate:Sub)Template:Ref
Scheme Template:N/a
ISLISP
Pascal recordTemplate:Indentname: type;Template:Indent...
end
Template:N/a Template:N/a recordTemplate:Indentcase type ofTemplate:Indentvalue: (types);Template:Indent...
end
Visual Basic
Visual Basic .NET Structure nameTemplate:IndentDim name As typeTemplate:Indent...
End Structure
(valTemplate:Sub, valTemplate:Sub, ... )
Python Template:N/aTemplate:Ref «(»valTemplate:Sub, valTemplate:Sub, valTemplate:Sub, ... «)» Template:N/a
S-Lang struct {name [=value], ...}
Fortran TYPE nameTemplate:Indenttype :: nameTemplate:Indent...
END TYPE
PHP Template:N/aTemplate:Ref
Perl Template:N/aTemplate:Ref rowspan=3 Template:N/a
Raku Template:N/aTemplate:Ref
Ruby Template:Code
Scala case class namevar» name: type, ...) (valTemplate:Sub, valTemplate:Sub, valTemplate:Sub, ... ) abstract class nameTemplate:Indentcase class Fooparameters») extends nameTemplate:Indentcase class Barparameters») extends nameTemplate:Indent...
or
abstract class nameTemplate:Indentcase object Foo extends nameTemplate:Indentcase object Bar extends nameTemplate:Indent...
or a combination of case classes and case objects
Windows PowerShell
OCaml type name = {«mutable» name : type;...} «(»valTemplate:Sub, valTemplate:Sub, valTemplate:Sub, ... «)» type name = Foo «of type» Template:Pipe Bar «of type» Template:Pipe ... rowspan=4 Template:N/a
F#
Standard ML type name = {name : type,...} (valTemplate:Sub, valTemplate:Sub, valTemplate:Sub, ... ) datatype name = Foo «of type» Template:Pipe Bar «of type» Template:Pipe ...
Haskell data Name = Constr {name :: type,...} data Name = Foo «types» Template:Pipe Bar «types» Template:Pipe ...
COBOL level-number name type clauses.Template:Indentlevel-number+n name type clauses.Template:Indent... Template:N/a Template:N/a name REDEFINES variable type.
  • Template:Note Only classes are supported.
  • Template:Note structs in C++ are actually classes, but have default public visibility and are also POD objects. C++11 extended this further, to make classes act identically to POD objects in many more cases.
  • Template:Note pair only
  • Template:Note Although Perl doesn't have records, because Perl's type system allows different data types to be in an array, "hashes" (associative arrays) that don't have a variable index would effectively be the same as records.
  • Template:Note Enumerations in this language are algebraic types with only nullary constructors

Variable and constant declarations

variable constant type synonym
Ada[1] identifier : type« := initial_value»Template:Ref identifier : constant type := final_value subtype identifier is type
ALGOL 68 modename name« := initial_value»; modename name = value; mode synonym = modename;
C (C99) type name« = initial_value»; enum{ name = value }; typedef type synonym;
Objective-C
C++ const type name = value;
C# type name1« = initial_value», name2« = initial_value», ...;
or
var name = initial_value;
const type name = value, name = value, ...;
or
readonly type name = value, name = value, ... ;
using synonym = type;
D type name« = initial_value»;
or
auto name = value;
const type name = value;
or
immutable type name = value;
alias type synonym;
Java type name« = initial_value»; final type name = value; rowspan=2 Template:N/a
JavaScript var name« = initial_value»; or
let name« = initial_value»; (since ECMAScript 2015)
const name = value; (since ECMAScript 2015)
Go var name type« = initial_value»
or
name := initial_value
const name «type» = value type synonym type
RustTemplate:Ref let mut name«: type»« = initial_value»;
static mut NAME: type = value;
let name«: type»« = initial_value»;
const NAME: type = value;

static NAME: type = value;
type synonym = typename;
Swift var name «: type»« = initial_value» let name «: type» = value typealias synonym = type
Common Lisp (defparameter name initial-value)
or
(defvar name initial-value)
(defconstant name value) (deftype synonym () 'type)
Scheme (define name initial_value)
ISLISP (defglobal name initial_value)
or
(defdynamic name initial_value)
(defconstant name value) Template:N/a
PascalTemplate:Ref name: type« = initial_value» name = value synonym = type
Visual Basic Dim name «As type» See notes to left.

Constants use the same syntax, and:

  • use Const instead of Dim
  • have a restriction to only certain primitive types
    Const name1 «As type» = value, name2 «As type» = value, ...
Visual Basic .NET[10] The variable declaration syntax of VB.NET is unusually difficult to precisely describe.

Given that there exist the identifier suffixes ("modifiers"):

  • type_character, available as an alternative to an As clause for some primitive data types;
  • nullable_specifier; and
  • array_specifier;

and that

  • a modified_identifier is of the form identifier«type_character»«nullable_specifier»«array_specifier»;
  • a modified_identifier_list is a comma-separated list of two or more occurrences of modified_identifier; and
  • a declarator_list is a comma-separated list of declarators, which can be of the form
    • identifier As object_creation_expression (object initializer declarator),
    • modified_identifier «As non_array_type«array_rank_specifier»»« = initial_value» (single declarator), or
    • modified_identifier_list «As «non_array_type««array_rank_specifier»» (multiple declarator);

valid declaration statements are of the form Template:In5Dim declarator_list, where, for the purpose of semantic analysis, to convert the declarator_list to a list of only single declarators:

  • The As clauses of each multiple declarator is distributed over its modified_identifier_list
  • The As New type... of each object initializer declarator is replaced with As type = New type...

and for which, for each identifier,

  • a type_character and As clause do not both appear;
  • if an As clause is present,
    • an array_rank_specifier does not appear both as a modification of the identifier and on the type of the As clause;
  • an unmodified_type can be determined, by the rule that,
    • if a type_character or As clause is present,
      • unmodified_type is that specified by such construct,
    • and that otherwise,
      • either Option Infer must be on and the identifier must have an initializer, in which case unmodified_type is that of the initializer, or
      • Option Strict must be off, in which case unmodified_type is Object;
  • its final_type is its unmodified_type prepended before its modifiers;
  • its final_type is a valid type; and
  • if an initial_value is present,
    • either Option Strict is on and initial_value has a widening conversion to final_type, or
    • Option Strict is off and initial_value has a narrowing conversion to final_type.

If Option Explicit is off, variables do not require explicit declaration; they are declared implicitly when used: name = initial_value

Imports synonym = type
Xojo Dim name «As type»« = initial_value» Template:N/a
Python name«: type» = initial_value rowspan=2 Template:N/a synonym = typeTemplate:Ref
CoffeeScript name = initial_value
S-Lang name = initial_value; typedef struct {...} typename
Fortran type :: name type, PARAMETER :: name = value
PHP $name = initial_value; define("name", value);
const name = value (5.3+)
rowspan=2 Template:N/a
Perl «my» $name« = initial_value»;Template:Ref use constant name => value;
Raku «my «type»» $name« = initial_value»;Template:Ref «my «type»» constant name = value; ::synonym ::= type
Ruby name = initial_value Name = value synonym = typeTemplate:Ref
Scala var name«: type» = initial_value val name«: type» = value type synonym = type
Windows PowerShell «[type]» $name = initial_value Template:N/a Template:N/a
Bash shell name=initial_value Template:N/a Template:N/a
OCaml let name« : type ref» = ref valueTemplate:Ref let name «: type» = value type synonym = type
F# let mutable name «: type» = value
Standard ML val name «: type ref» = ref valueTemplate:Ref val name «: type» = value
Haskell «name::typename = value type Synonym = type
Forth VARIABLE name (in some systems use value VARIABLE name instead) value CONSTANT name
COBOL level-number name type clauses. «0»1 name CONSTANT «AS» value. level-number name type clauses «IS» TYPEDEF.
Mathematica name=initial_value Template:N/a Template:N/a
  • Template:Note Pascal has declaration blocks. See functions.
  • Template:NoteTypes are just regular objects, so you can just assign them.
  • Template:Note In Perl, the "my" keyword scopes the variable into the block.
  • Template:Note Technically, this does not declare name to be a mutable variable—in ML, all names can only be bound once; rather, it declares name to point to a "reference" data structure, which is a simple mutable cell. The data structure can then be read and written to using the ! and := operators, respectively.
  • Template:Note If no initial value is given, an invalid value is automatically assigned (which will trigger a run-time exception if it used before a valid value has been assigned). While this behaviour can be suppressed it is recommended in the interest of predictability. If no invalid value can be found for a type (for example in case of an unconstraint integer type), a valid, yet predictable value is chosen instead.
  • Template:Note In Rust, if no initial value is given to a let or let mut variable and it is never assigned to later, there is an "unused variable" warning. If no value is provided for a const or static or static mut variable, there is an error. There is a "non-upper-case globals" error for non-uppercase const variables. After it is defined, a static mut variable can only be assigned to in an unsafe block or function.

Conditional statements

if else if select case conditional expression
Ada[1] if condition thenTemplate:Indentstatements
«elseTemplate:Indentstatements»
end if
if conditionTemplate:Sub thenTemplate:Indentstatements
elsif conditionTemplate:Sub thenTemplate:Indentstatements
...
«elseTemplate:Indentstatements»
end if
case expression isTemplate:Indentwhen value_listTemplate:Sub => statementsTemplate:Indentwhen value_listTemplate:Sub => statementsTemplate:Indent...Template:Indent«when others => statements»
end case
(if conditionTemplate:Sub thenTemplate:IndentexpressionTemplate:Sub
«elsif conditionTemplate:Sub thenTemplate:IndentexpressionTemplate:Sub»
...
elseTemplate:IndentexpressionTemplate:Sub
)

or
(case expression isTemplate:Indentwhen value_listTemplate:Sub => expressionTemplate:SubTemplate:Indentwhen value_listTemplate:Sub => expressionTemplate:SubTemplate:Indent...Template:Indent«when others => expressionTemplate:Sub»
)
Seed7 if condition thenTemplate:Indentstatements
«elseTemplate:Indentstatements»
end if
if conditionTemplate:Sub thenTemplate:Indentstatements
elsif conditionTemplate:Sub thenTemplate:Indentstatements
...
«elseTemplate:Indentstatements»
end if
case expression ofTemplate:Indentwhen set1 : statementsTemplate:Indent...Template:Indent«otherwise: statements»
end case
Modula-2 if condition thenTemplate:Indentstatements
«elseTemplate:Indentstatements»
end
if conditionTemplate:Sub thenTemplate:Indentstatements
elsif conditionTemplate:Sub thenTemplate:Indentstatements
...
«elseTemplate:Indentstatements»
end
case expression ofTemplate:IndentcaseLabelList : statements Template:PipeTemplate:Indent...Template:Indent«else statements»
end
ALGOL 68 if condition then statements «else statements» fi if condition then statements elif condition then statements fi case switch in statements, statements«,... out statements» esac ( condition | valueIfTrue | valueIfFalse )
ALGOL 68
(brief form)
( condition | statements «| statements» ) ( condition | statements |: condition | statements ) ( variable | statements,... «| statements» )
APL :If conditionTemplate:Indentinstructions
«:ElseTemplate:Indentinstructions»
:EndIf
:If conditionTemplate:Indentinstructions
:ElseIf conditionTemplate:Indentinstructions
...
«:ElseTemplate:Indentinstructions»
:EndIf
:Select expressionTemplate:Indent:Case case1Template:IndentinstructionsTemplate:Indent...Template:Indent«:ElseTemplate:Indentinstructions»
:EndSelect
{condition:valueIfTruevalueIfFalse}
C (C99) if (condition) instructions
«else instructions»

instructions can be a single statement or a block in the form of: { statements }
if (condition) instructions
else if (condition) instructions
...
«else instructions»

or
if (condition) instructions
else { if (condition) instructions }
switch (variable) { Template:Indentcase case1: instructions «; break;»Template:Indent...Template:Indent«default: instructions»
}
condition ? valueIfTrue : valueIfFalse
Objective-C
C++ (STL)
D
Java
JavaScript
PHP
C# if (condition) instructions
«else instructions»

instructions can be a single statement or a block in the form of: { statements }

if (condition) instructions
else if (condition) instructions
...
«else instructions»
switch (variable)
{ Template:Indentcase caseTemplate:Sub:Template:IndentinstructionsTemplate:Indent«break_or_jump_statement»Template:Indent...Template:Indent«default:Template:IndentinstructionsTemplate:Indentbreak_or_jump_statement»
}

All non-empty cases must end with a break or goto case statement (that is, they are not allowed to fall-through to the next case). The default case is not required to come last.

condition ? valueIfTrue : valueIfFalse
Windows PowerShell if (condition) instruction
«else instructions»
if (condition) { instructions }
elseif (condition) { instructions }
...
«else { instructions
switch (variable) { case1{instructions «break;» } ... «default { instructions }»}
Go if condition {instructions}
«else {instructions
if condition {instructions}
else if condition {instructions}
...
«else {instructions

or
switch { Template:Indentcase condition: instructionsTemplate:Indent...Template:Indent«default: instructions»
}
switch variable { Template:Indentcase case1: instructionsTemplate:Indent...Template:Indent«default: instructions»
}
Swift if condition {instructions}
«else {instructions
if condition {instructions}
else if condition {instructions}
...
«else {instructions
switch variable { Template:Indentcase case1: instructionsTemplate:Indent...Template:Indent«default: instructions»
}
Perl if (condition) {instructions}
«else {instructions

or
unless (notcondition) {instructions}
«else {instructions
if (condition) {instructions}
elsif (condition) {instructions}
...
«else {instructions

or
unless (notcondition) {instructions}
elsif (condition) {instructions}
...
«else {instructions
use feature "switch";
...
given (variable) { Template:Indentwhen (case1) { instructions }Template:Indent...Template:Indent«default { instructions
}
condition ? valueIfTrue : valueIfFalse
Raku if condition {instructions}
«else {instructions

or
unless notcondition {instructions}
if condition {instructions}
elsif condition {instructions}
...
«else {instructions}
given variable { Template:Indentwhen case1 { instructions }Template:Indent...Template:Indent«default { instructions
}
condition ?? valueIfTrue !! valueIfFalse
Ruby if conditionTemplate:Indentinstructions
«elseTemplate:Indentinstructions»
if conditionTemplate:Indentinstructions
elsif conditionTemplate:Indentinstructions
...
«elseTemplate:Indentinstructions»
end
case variableTemplate:Indentwhen case1Template:IndentinstructionsTemplate:Indent...Template:Indent«elseTemplate:Indentinstructions»
end
condition ? valueIfTrue : valueIfFalse
Scala if (condition) {instructions}
«else {instructions
if (condition) {instructions}
else if (condition) {instructions}
...
«else {instructions
expression match { Template:Indentcase pattern1 => expressionTemplate:Indentcase pattern2 => expressionTemplate:Indent...Template:Indent«case _ => expression»
}
Template:Ref
if (condition) valueIfTrue else valueIfFalse
Smalltalk condition ifTrue:Template:IndenttrueBlock
«ifFalse:Template:IndentfalseBlock»
end
condition ifTrue: trueBlock ifFalse: falseBlock
Common Lisp (when conditionTemplate:Indentinstructions)
or
(unless conditionTemplate:Indentinstructions)
or
(if conditionTemplate:Indent(progn instructions)Template:Indent«(progn instructions)»)
(cond (condition1 instructions)Template:Indent(condition2 instructions)Template:Indent...Template:Indent«(t instructions)») (case expressionTemplate:Indent(case1 instructions)Template:Indent(case2 instructions)Template:Indent...Template:Indent«(otherwise instructions)») (if test then else)
or
(cond (test1 value1) (test2 value2) ...))
Scheme (when condition instructions)
or
(if condition (begin instructions) «(begin instructions)»)
(cond (condition1 instructions) (condition2 instructions) ... «(else instructions)») (case (variable) ((case1) instructions) ((case2) instructions) ... «(else instructions)») (if condition valueIfTrue valueIfFalse)
ISLISP (if conditionTemplate:Indent(progn instructions)Template:Indent«(progn instructions)») (cond (condition1 instructions)Template:Indent(condition2 instructions)Template:Indent...Template:Indent«(t instructions)») (case expressionTemplate:Indent(case1 instructions)Template:Indent(case2 instructions)Template:Indent...Template:Indent«(t instructions)») (if condition valueIfTrue valueIfFalse)
Pascal if condition then beginTemplate:Indentinstructions
end
«else beginTemplate:Indentinstructions
end»'
Template:Ref
if condition then beginTemplate:Indentinstructions
end
else if condition then beginTemplate:Indentinstructions
end
...
«else beginTemplate:Indentinstructions
end»
Template:Ref
case variable ofTemplate:Indentcase1: instructionsTemplate:Indent...Template:Indent«else: instructions»
end
Template:Ref
Visual Basic If condition ThenTemplate:Indentinstructions
«ElseTemplate:Indentinstructions»
End If

Single-line, when instructions are instructionTemplate:Sub : instructionTemplate:Sub : ...:
If condition Then instructions «Else instructions»
If condition ThenTemplate:Indentinstructions
ElseIf condition ThenTemplate:Indentinstructions
...
«ElseTemplate:Indentinstructions»
End If

Single-line:
See note about C-like languages; the Else clause of a single-line If statement can contain another single-line If statement.
Select« Case» variableTemplate:IndentCase case_patternTemplate:SubTemplate:IndentinstructionsTemplate:Indent...Template:Indent«Case ElseTemplate:Indentinstructions»
End Select
IIf(condition, valueIfTrue, valueIfFalse)
Visual Basic .NET If(condition, valueIfTrue, valueIfFalse)
Xojo
PythonTemplate:Ref if condition :
Template:Keypressinstructions
«else:
Template:Keypressinstructions»
if condition :
Template:Keypressinstructions
elif condition :
Template:Keypressinstructions
...
«else:
Template:Keypressinstructions»
Python 3.10+:
match variable:
Template:Keypresscase case1:
Template:KeypressTemplate:Keypressinstructions
Template:Keypresscase case2:
Template:KeypressTemplate:Keypressinstructions
Python 2.5+:
valueIfTrue if condition else valueIfFalse
S-Lang if (condition) { instructions } «else { instructions if (condition) { instructions } else if (condition) { instructions } ... «else { instructions switch (variable) { case case1: instructions } { case case2: instructions } ...
Fortran IF (condition) THENTemplate:Indentinstructions
ELSETemplate:Indentinstructions
ENDIF
IF (condition) THENTemplate:Indentinstructions
ELSEIF (condition) THENTemplate:Indentinstructions
...
ELSETemplate:Indentinstructions
ENDIF
SELECT CASE(variable)Template:IndentCASE (case1)Template:IndentinstructionsTemplate:Indent...Template:IndentCASE DEFAULTTemplate:Indentinstructions
END SELECT
Forth condition IF instructions « ELSE instructions» THEN condition IF instructions ELSE condition IF instructions THEN THEN value CASETemplate:Indentcase OF instructions ENDOFTemplate:Indentcase OF instructions ENDOFTemplate:Indentdefault instructions
ENDCASE
condition IF valueIfTrue ELSE valueIfFalse THEN
OCaml if condition then begin instructions end «else begin instructions end» if condition then begin instructions end else if condition then begin instructions end ... «else begin instructions end» match value with Template:Indentpattern1 -> expressionTemplate:IndentTemplate:Pipe pattern2 -> expressionTemplate:Indent...Template:Indent«Template:Pipe _ -> expression»Template:Ref if condition then valueIfTrue else valueIfFalse
F# Lightweight syntax mode:

Either on a single line or with indentation as shown below: if condition then
Template:Keypressinstructions
«else
Template:Keypressinstructions»

Verbose syntax mode:
Same as Standard ML.

Lightweight syntax mode:
Either on a single line or with indentation as shown below:
if condition then
Template:Keypressinstructions
elif condition then
Template:Keypressinstructions
...
«else
Template:Keypressinstructions»

Verbose syntax mode:
Same as Standard ML.
Standard ML if condition then «(»instructions «
else «(» instructions «
if condition then «(»instructions «
else if condition then «(» instructions «
...
else «(» instructions «
case value ofTemplate:Indentpattern1 => expressionTemplate:IndentTemplate:Pipe pattern2 => expressionTemplate:Indent...Template:Indent«Template:Pipe _ => expression»Template:Ref
Haskell (GHC) if condition then expression else expression
or
when condition (do instructions)
or
unless notcondition (do instructions)
result Template:Pipe condition = expressionTemplate:IndentTemplate:Pipe condition = expressionTemplate:IndentTemplate:Pipe otherwise = expression case value of { Template:Indentpattern1 -> expression;Template:Indentpattern2 -> expression;Template:Indent...Template:Indent«_ -> expression»
}
Template:Ref
Bash shell if condition-command; thenTemplate:Indentexpression
«elseTemplate:Indentexpression»
fi
if condition-command; thenTemplate:Indentexpression
elif condition-command; thenTemplate:Indentexpression
«elseTemplate:Indentexpression»
fi
case "$variable" inTemplate:Indent"$condition1" )Template:Indentcommand...Template:Indent"$condition2" )Template:Indentcommand...
esac
CoffeeScript if condition then expression «else expression»
or
if conditionTemplate:Indentexpression
«elseTemplate:Indentexpression»

or
expression if condition
or
unless conditionTemplate:Indentexpression
«elseTemplate:Indentexpression»

or
expression unless condition
if condition then expression else if condition then expression «else expression»
or
if conditionTemplate:Indentexpression
else if conditionTemplate:Indentexpression
«elseTemplate:Indentexpression»

or
unless conditionTemplate:Indentexpression
else unless conditionTemplate:Indentexpression
«elseTemplate:Indentexpression»
switch expressionTemplate:Indentwhen condition then expressionTemplate:Indentelse expression
or
switch expressionTemplate:Indentwhen conditionTemplate:IndentexpressionTemplate:Indent«elseTemplate:Indentexpression»
All conditions are expressions.
COBOL IF condition «THEN»Template:Indentexpression
«ELSETemplate:Indentexpression».
Template:Ref
EVALUATE expression «ALSO expression...»Template:IndentWHEN case-or-condition «ALSO case-or-condition...»Template:IndentexpressionTemplate:Indent...Template:Indent«WHEN OTHERTemplate:Indentexpression»
END-EVALUATE
Rust if condition { Template:Indentexpression
}« else { Template:Indentexpression
if condition { Template:Indentexpression
} else if condition {Template:Indentexpression
}« else {Template:Indentexpression
}»
match variable { Template:Indentpattern1 => expression,Template:Indentpattern2 => expression,Template:Indentpattern3 => expression,Template:Indent«_ => expression»
}
Template:RefTemplate:Ref
All conditions are expressions
if else if select case conditional expression
  • Template:Note A single instruction can be written on the same line following the colon. Multiple instructions are grouped together in a block which starts on a newline (The indentation is required). The conditional expression syntax does not follow this rule.
  • Template:Note This is pattern matching and is similar to select case but not the same. It is usually used to deconstruct algebraic data types.
  • Template:Note In languages of the Pascal family, the semicolon is not part of the statement. It is a separator between statements, not a terminator.
  • Template:Note END-IF may be used instead of the period at the end.
  • Template:Note In Rust, the comma (,) at the end of a match arm can be omitted after the last match arm, or after any match arm in which the expression is a block (ends in possibly empty matching brackets {}).
while loop do while loop (count-controlled) for loop foreach
Ada[1] while condition loopTemplate:Indentstatements
end loop
loopTemplate:IndentstatementsTemplate:Indentexit when not condition
end loop
for index in «reverse» [first .. last Template:Pipe discrete_type] loopTemplate:Indentstatements
end loop
for item of «reverse» iterator loopTemplate:Indentstatements
end loop

or
(for [all Template:Pipe some] [in Template:Pipe of] [first .. last Template:Pipe discrete_type Template:Pipe iterator] => predicate)Template:Ref
ALGOL 68 «for index» «from first» «by increment» «to last» «while condition» do statements od for key «to upb list» do «typename val=list[key];» statements od
«while condition»Template:Indentdo statements od «while statements; condition»Template:Indentdo statements od «for index» «from first» «by increment» «to last» do statements od
APL :While conditionTemplate:Indentstatements
:EndWhile
:RepeatTemplate:Indentstatements
:Until condition
:For var«s» :In listTemplate:Indentstatements
:EndFor
:For var«s» :InEach listTemplate:Indentstatements
:EndFor
C (C99) instructions can be a single statement or a block in the form of: { statements }
while (condition) instructions
do instructions while (condition); for («type» i = first; i <= last; i++) instructions Template:N/a
Objective-C for (type item in set) instructions
C++ (STL) «std::»for_each(start, end, function)
Since C++11:
for (type item : set) instructions
C# foreach (type item in set) instructions
Java for (type item : set) instructions
JavaScript for (var i = first; i <= last; i++) instructions Since EcmaScript 2015:[11]

for (var item of set) instructions

PHP foreach (range(first, last) as $i) instructions
or
for ($i = first; $i <= last; $i++) instructions
foreach (set as item) instructions
or
foreach (set as key => item) instructions
Windows PowerShell for ($i = first; $i -le last; $i++) instructions foreach (item in set) instructions
D foreach (i; first ... last) instructions foreach («type» item; set) instructions
Go for condition { instructions } for i := first; i <= last; i++ { instructions } for key, item := range set { instructions }
Swift while condition { instructions } 2.x:
repeat { instructions } while condition
1.x:
do { instructions } while condition
for i = first ... last { instructions }
or
for i = first ..< last+1 { instructions }
or
for var i = first; i <= last; i++ { instructions }
for item in set { instructions }
Perl while (condition) { instructions }
or
until (notcondition) { instructions }
do { instructions } while (condition)
or
do { instructions } until (notcondition)
for«each» «$i» (first .. last) { instructions }
or
for ($i = first; $i <= last; $i++) { instructions }
for«each» «$item» (set) { instructions }
Raku while condition { instructions }
or
until notcondition { instructions }
repeat { instructions } while condition
or
repeat { instructions } until notcondition
for first..last -> $i { instructions }
or
loop ($i = first; $i <=last; $i++) { instructions }
for set« -> $item» { instructions }
Ruby while conditionTemplate:Indentinstructions
end

or
until notconditionTemplate:Indentinstructions
end
beginTemplate:Indentinstructions
end while condition

or
beginTemplate:Indentinstructions
end until notcondition
for i in first..lastTemplate:Indentinstructions
end

or
for i in first...last+1Template:Indentinstructions
end

or
first.Template:Not a typo(last) { Template:PipeiTemplate:Pipe instructions }
for item in setTemplate:Indentinstructions
end

or
set.each { Template:PipeitemTemplate:Pipe instructions }
Bash shell while condition ;doTemplate:Indentinstructions
done

or
until notcondition ;doTemplate:Indentinstructions
done
Template:N/a for ((i = first; i <= last; ++i)) ; doTemplate:Indentinstructions
done
for item in set ;doTemplate:Indentinstructions
done
Scala while (condition) { instructions } do { instructions } while (condition) for (i <- first to last «by 1») { instructions }
or
first to last «by 1» foreach (i => { instructions })
for (item <- set) { instructions }
or
set foreach (item => { instructions })
Smalltalk conditionBlock whileTrue:Template:IndentloopBlock loopBlock doWhile:Template:IndentconditionBlock first to: last do:Template:IndentloopBlock collection do:Template:IndentloopBlock
Common Lisp (loopTemplate:Indentwhile conditionTemplate:IndentdoTemplate:Indentinstructions)
or
(do () (notcondition)Template:Indentinstructions)
(loopTemplate:IndentdoTemplate:IndentinstructionsTemplate:Indentwhile condition) (loopTemplate:Indentfor i from first to last «by 1»Template:IndentdoTemplate:Indentinstructions)
or
(dotimes (i N)Template:Indentinstructions)
or
(do ((i first (1+ i))) ((>=i last))
Template:Indentinstructions)
(loopTemplate:Indentfor item in listTemplate:IndentdoTemplate:Indentinstructions)
or
(loopTemplate:Indentfor item across vectorTemplate:IndentdoTemplate:Indentinstructions)
or
(dolist (item list)Template:Indentinstructions)
or
(mapc function list)
or
(map type function sequence)
Scheme (do () (notcondition) instructions)
or
(let loop () (if condition (begin instructions (loop))))
(let loop () (instructions (if condition (loop)))) (do ((i first (+ i 1))) ((>= i last)) instructions)
or
(let loop ((i first)) (if (< i last) (begin instructions (loop (+ i 1)))))
(for-each (lambda (item) instructions) list)
ISLISP (while condition instructions) (tagbody loop instructions (if condition (go loop)) (for ((i first (+ i 1))) ((>= i last)) instructions) (mapc (lambda (item) instructions) list)
Pascal while condition do beginTemplate:Indentinstructions
end
repeatTemplate:Indentinstructions
until notcondition;
for i := first «step 1» to last do beginTemplate:Indentinstructions
end;
Template:Ref
for item in set do instructions
Visual Basic Do While conditionTemplate:Indentinstructions
Loop

or
Do Until notconditionTemplate:Indentinstructions
Loop

or
While conditionTemplate:Indentinstructions
Wend
(Visual Basic .NET uses End While instead)
DoTemplate:Indentinstructions
Loop While condition

or
DoTemplate:Indentinstructions
Loop Until notcondition
i must be declared beforehand.

For i = first To last «Step Template:Indentinstructions
Next i

For Each item In setTemplate:Indentinstructions
Next item
Visual Basic .NET For i« As type» = first To last« Step Template:Indentinstructions
Next« i»
Template:Ref
For Each item« As type» In setTemplate:Indentinstructions
Next« item»
Xojo While conditionTemplate:Indentinstructions
Wend
Do Until notconditionTemplate:Indentinstructions
Loop

or
DoTemplate:Indentinstructions
Loop Until notcondition
Python while condition :
Template:Keypressinstructions
«else:
Template:Keypressinstructions»
Template:N/a Python 3.x:
for i in range(first, last+1):
Template:Keypressinstructions
«else:
Template:Keypressinstructions»

Python 2.x:
for i in xrange(first, last+1):
Template:Keypressinstructions
«else:
Template:Keypressinstructions»
for item in set:
Template:Keypressinstructions
«else:
Template:Keypressinstructions»
S-Lang while (condition) { instructions } «then optional-block» do { instructions } while (condition) «then optional-block» for (i = first; i <= last; i++) { instructions } «then optional-block» foreach item(set) «using (what)» { instructions } «then optional-block»
Fortran DO WHILE (condition)Template:Indentinstructions
ENDDO
DOTemplate:IndentinstructionsTemplate:IndentIF (condition) EXIT
ENDDO
DO I = first,lastTemplate:Indentinstructions
ENDDO
Template:N/a
Forth BEGIN «instructions» condition WHILE instructions REPEAT BEGIN instructions condition UNTIL limit start DO instructions LOOP Template:N/a
OCaml while condition do instructions done Template:N/a for i = first to last do instructions done Array.iter (fun item -> instructions) array
or
List.iter (fun item -> instructions) list
F# while condition do
Template:Keypressinstructions
Template:N/a for i = first to last do
Template:Keypressinstructions
foritem in set do
Template:Keypressinstructions

or
Seq.iter (fun item -> instructions) set
Standard ML while condition do ( instructions ) colspan=2 Template:N/a Array.app (fn item => instructions) array
or
app (fn item => instructions) list
Haskell (GHC) colspan=2 Template:N/a Control.Monad.forM_ [first..last] (\i -> do instructions) Control.Monad.forM_list (\item -> do instructions)
Eiffel fromTemplate:Indentsetup
untilTemplate:Indentcondition
loopTemplate:Indentinstructions
end
CoffeeScript while conditionTemplate:Indentexpression
or
expression while condition
or
while condition then expression
or
until conditionTemplate:Indentexpression
or
expression until condition
or
until expression then condition
Template:N/a for i in [first..last]Template:Indentexpression
or
for i in [first..last] then expression
or
expression for i in [first..last]
for item in setTemplate:Indentexpression
or
for item in set then expression
or
expression for item in set
COBOL PERFORM procedure-1 «THROUGH procedure-2» ««WITH» TEST BEFORE» UNTIL conditionTemplate:Ref
or
PERFORM ««WITH» TEST BEFORE» UNTIL conditionTemplate:Indentexpression
END-PERFORM
PERFORM procedure-1 «THROUGH procedure-2» «WITH» TEST AFTER UNTIL conditionTemplate:Ref
or
PERFORM «WITH» TEST AFTER UNTIL conditionTemplate:Indentexpression
END-PERFORM
PERFORM procedure-1 «THROUGH procedure-2» VARYING i FROM first BY increment UNTIL i > lastTemplate:Ref
or
PERFORM VARYING i FROM first BY increment UNTIL i > lastTemplate:Indentexpression
END-PERFORM
Template:Ref
Template:N/a
Rust while condition { Template:Indentexpression
}
loop { Template:IndentexpressionTemplate:Indentif condition { Template:Indentbreak;Template:Indent}
}
for i in first..last+1 { Template:Indentexpression
}

or
for i in first..=last { Template:Indentexpression
}
for item in set { Template:Indentexpression
}
Template:Ref
or
set.into_iter().for_each(Template:PipeitemTemplate:Pipe expression);Template:Ref

Template:Further

throw handler assertion
Ada[1] raise exception_name «with string_expression» beginTemplate:Indentstatements
exceptionTemplate:Indentwhen exception_list1 => statements;Template:Indentwhen exception_list2 => statements;
...Template:Indent«when others => statements;»
end
Template:Ref
pragma Assert («Check =>» boolean_expression ««Message =>» string_expression»)
[function Template:Pipe procedure Template:Pipe entry] withTemplate:IndentPre => boolean_expressionTemplate:IndentPost => boolean_expression
any_type with Type_Invariant => boolean_expression
APL «string_expression» ⎕SIGNAL number_expression :Trap number«s»_expressionTemplate:Indentstatements
«:Case number«s»_expressionTemplate:Indentstatements»
...
«:Else number«s»_expressionTemplate:Indentstatements»
:EndTrap
«string_expression» ⎕SIGNAL 98/⍨~condition
C (C99) longjmp(state, exception); switch (setjmp(state)) { case 0: instructions break; case exception: instructions ... } assert(condition);
C++ throw exception; try { instructions } catch «(exception)» { instructions } ...
C# try { instructions } catch «(exception« name»)» { instructions } ... «finally { instructions System.Diagnostics.Debug.Assert(condition);
or
System.Diagnostics.Trace.Assert(condition);
Java try { instructions } catch (exception) { instructions } ... «finally { instructions assert condition «: description»;
JavaScript try { instructions } catch (exception) { instructions} «finally { instructions Template:Dunno
D try { instructions } catch (exception) { instructions } ... «finally { instructions assert(condition);
PHP try { instructions } catch (exception) { instructions } ... «finally { instructions assert(condition);
S-Lang try { instructions } catch «exception» { instructions } ... «finally { instructions Template:Dunno
Windows PowerShell trap «[exception]» { instructions } ... instructions
or
try { instructions } catch «[exception]» { instructions } ... «finally { instructions
[Debug]::Assert(condition)
Objective-C @throw exception; @try { instructions } @catch (exception) { instructions } ... «@finally { instructions NSAssert(condition, description);
Swift throw exception (2.x) do { try expression ... instructions } catch exception { instructions } ... (2.x) assert(condition«, description»)
Perl die exception; eval { instructions }; if ($@) { instructions } Template:Dunno
Raku try { instructions CATCH { when exception { instructions } ...}} Template:Dunno
Ruby raise exception beginTemplate:Indentinstructions
rescue exceptionTemplate:Indentinstructions
...
«elseTemplate:Indentinstructions»
«ensureTemplate:Indentinstructions»
end
Smalltalk exception raise instructionBlock on: exception do: handlerBlock assert: conditionBlock
Common Lisp (error "exception")
or
(errorTemplate:IndenttypeTemplate:Indentarguments)
or
(error (make-conditionTemplate:IndenttypeTemplate:Indentarguments))
(handler-caseTemplate:Indent(progn instructions)Template:Indent(exception instructions)Template:Indent...)
or
(handler-bindTemplate:Indent(conditionTemplate:Indent(lambdaTemplate:IndentinstructionsTemplate:Indent«invoke-restart restart args»))
...)
Template:Ref
(assert condition)
or
(assert conditionTemplate:Indent«(place)Template:Indent«error»»)
or
(check-type var type)
Scheme (R6RS) (raise exception) (guard (con (condition instructions) ...) instructions) Template:Dunno
ISLISP (error "error-string" objects)
or
(signal-condition condition continuable)
(with-handlerTemplate:Indenthandler form*
)
Template:Dunno
Pascal raise Exception.Create() try Except on E: exception do begin instructions end; end; Template:Dunno
Visual Basic Err.Raise ERRORNUMBER With New Try: On Error Resume NextTemplate:IndentOneInstruction
.Catch
: On Error GoTo 0: Select Case .NumberTemplate:IndentCase SOME_ERRORNUMBERTemplate:Indentinstructions
End Select: End With
'*** Try class ***
Private mstrDescription As String
Private mlngNumber As Long

Public Sub Catch()
    mstrDescription = Err.Description
    mlngNumber = Err.Number
End Sub

Public Property Get Number() As Long
    Number = mlngNumber
End Property

Public Property Get Description() As String
    Description = mstrDescription
End Property
[12]
Debug.Assert condition
Visual Basic .NET Throw exception
or
Error errorcode
TryTemplate:Indentinstructions
Catch« name As exception»« When condition»Template:Indentinstructions
...
«FinallyTemplate:Indentinstructions»
End Try
System.Diagnostics.Debug.Assert(condition)
or
System.Diagnostics.Trace.Assert(condition)
Xojo Raise exception TryTemplate:Indentinstructions
Catch «exception»Template:Indentinstructions
...
«FinallyTemplate:Indentinstructions»
End Try
Template:N/a
Python raise exception try:
Template:Keypressinstructions
except «exception»:
Template:Keypressinstructions
...
«else:
Template:Keypressinstructions»
«finally:
Template:Keypressinstructions»
assert condition
Fortran colspan=3 Template:N/a
Forth code THROW xt CATCH ( code or 0 ) Template:N/a
OCaml raise exception try expression with pattern -> expression ... assert condition
F# try expression with pattern -> expression ...
or
try expression finally expression
Standard ML raise exception «arg» expression handle pattern => expression ...
Haskell (GHC) throw exception
or
throwError expression
catch tryExpression catchExpression
or
catchError tryExpression catchExpression
assert condition expression
COBOL RAISE «EXCEPTION» exception USE «AFTER» EXCEPTION OBJECT class-name.
or
USE «AFTER» EO class-name.
or
USE «AFTER» EXCEPTION CONDITION exception-name «FILE file-name».
or
USE «AFTER» EC exception-name «FILE file-name».
Template:N/a
Rust colspan=2 Template:No[13] assert!(condition)
  • Template:Note Common Lisp allows with-simple-restart, restart-case and restart-bind to define restarts for use with invoke-restart. Unhandled conditions may cause the implementation to show a restarts menu to the user before unwinding the stack.
  • Template:Note Uncaught exceptions are propagated to the innermost dynamically enclosing execution. Exceptions are not propagated across tasks (unless these tasks are currently synchronised in a rendezvous).

Other control flow statements

exit block (break) continue label branch (goto) return value from generator
Ada[1] exit «loop_name» «when condition» Template:N/a label: goto label Template:N/a
ALGOL 68 value exit; ... do statements; skip exit; label: statements od label: ... go to label; ...
goto label; ...
label; ...
yield(value)

(Callback)[14]

APL :Leave :Continue label: label
or
:GoTo label
Template:N/a
C (C99) break; continue; label: goto label; rowspan=4 Template:N/a
Objective-C
C++ (STL)
D
C# yield return value;
Java break «label»; continue «label»; rowspan=2 Template:N/a
JavaScript yield value«;»
PHP break «levels»; continue «levels»; goto label; yield «key =>» value;
Perl last «label»; next «label»;
Raku
Go break «label» continue «label» goto label
Swift break «label» continue «label» Template:N/a
Bash shell break «levels» continue «levels» Template:N/a Template:N/a Template:N/a
Common Lisp (return)
or
(return-from block)
or
(loop-finish)
(tagbody tagTemplate:Indent...Template:Indenttag
...)
(go tag)
Scheme
ISLISP (return-from block) (tagbody tagTemplate:Indent...Template:Indenttag
...)
(go tag)
Pascal (ISO) colspan=2 Template:N/a label:Template:Ref goto label; rowspan=4 Template:N/a
Pascal (FPC) break; continue;
Visual Basic Exit blockAlternatively, for methods,
Return
Template:N/a label: GoTo label
Xojo Continue block
Visual Basic .NET Yield value
Python break continue colspan=2 Template:N/a yield value
RPG IV LEAVE; ITER;
S-Lang break; continue;
Fortran EXIT CYCLE labelTemplate:Ref GOTO label Template:N/a
Ruby break next
Windows PowerShell break «label» continue
OCaml rowspan=4 colspan=4 Template:N/a
F#
Standard ML
Haskell (GHC)
COBOL EXIT PERFORM or EXIT PARAGRAPH or EXIT SECTION or EXIT. EXIT PERFORM CYCLE label «SECTION». GO TO label Template:N/a

See reflective programming for calling and declaring functions by strings.

calling a function basic/void function value-returning function required main function
Ada[1] foo «(parameters)» procedure foo «(parameters)» is begin statements end foo function foo «(parameters)» return type is begin statements end foo Template:N/a
ALGOL 68 foo «(parameters)»; proc foo = «(parameters)» void: ( instructions ); proc foo = «(parameters)» rettype: ( instructions ...; retvalue ); Template:N/a
APL «parameters» foo parameters foo←{ statements } foo←{ statements } Template:N/a
C (C99) foo(«parameters») void foo(«parameters») { instructions } type foo(«parameters») { instructions ... return value; } «global declarations»
int main(«int argc, char *argv[]») { Template:Indentinstructions
}
Objective-C
C++ (STL)
Java public static void main(String[] args) { instructions }
or
public static void main(String... args) { instructions }
D int main(«char[][] args») { instructions}
or
int main(«string[] args») { instructions}
or
void main(«char[][] args») { instructions}
or
void main(«string[] args») { instructions}
C# Same as above; alternatively, if only one statement:

void foo(«parameters») => statement;

Same as above; alternatively, if simple enough to be an expression:

void foo(«parameters») => expression;

static void Main(«string[] args») method_body
May instead return int.
(starting with C# 7.1:) May return Task or Task<int>, and if so, may be async.
JavaScript function foo(«parameters») { instructions }
or
var foo = function («parameters») { instructions }
or
var foo = new Function ("«parameter»", ..., "«last parameter»" "instructions");
function foo(«parameters») { instructions ... return value; } Template:N/a
Go func foo(«parameters») { instructions } func foo(«parameters») type { instructions ... return value } func main() { instructions }
Swift func foo(«parameters») { instructions } func foo(«parameters») -> type { instructions ... return value } Template:N/a
Common Lisp (foo «parameters») (defun foo («parameters»)Template:Indentinstructions)
or
(setf (symbol-function 'symbol)Template:Indentfunction)
(defun foo («parameters»)Template:Indent...Template:Indentvalue) rowspan=3 Template:N/a
Scheme (define (foo parameters) instructions)
or
(define foo (lambda (parameters) instructions))
(define (foo parameters) instructions... return_value)
or
(define foo (lambda (parameters) instructions... return_value))
ISLISP (defun foo («parameters»)Template:Indentinstructions) (defun foo («parameters»)Template:Indent...Template:Indentvalue)
Pascal foo«(parameters procedure foo«(parameters)»; «forward;»Template:Ref
«labelTemplate:Indentlabel declarations»
«constTemplate:Indentconstant declarations»
«typeTemplate:Indenttype declarations»
«varTemplate:Indentvariable declarations»
«local function declarations»

beginTemplate:Indentinstructions
end;
function foo«(parameters)»: type; «forward;»Template:Ref
«labelTemplate:Indentlabel declarations»
«constTemplate:Indentconstant declarations»
«typeTemplate:Indenttype declarations»
«varTemplate:Indentvariable declarations»
«local function declarations»

beginTemplate:Indentinstructions;Template:Indentfoo := value
end;
program name;
«labelTemplate:Indentlabel declarations»
«constTemplate:Indentconstant declarations»
«typeTemplate:Indenttype declarations»
«varTemplate:Indentvariable declarations»
«function declarations»

beginTemplate:Indentinstructions
end.
Visual Basic Foo(«parameters») Sub Foo«(parametersTemplate:Indentinstructions
End Sub
Function Foo«(parameters)»« As type»Template:IndentinstructionsTemplate:IndentFoo = value
End Function
Sub Main()Template:Indentinstructions
End Sub
Visual Basic .NET Same as above; alternatively:

Function Foo«(parameters)»« As type»Template:IndentinstructionsTemplate:IndentReturn value
End Function

The As clause is not required if Option Strict is off. A type character may be used instead of the As clause.
If control exits the function without a return value having been explicitly specified, the function returns the default value for the return type.

Sub Main(««ByVal »args() As String»)Template:Indentinstructions
End Sub
or
Function Main(««ByVal »args() As String») As IntegerTemplate:Indentinstructions
End Function
Xojo
Python foo(«parameters») def foo(«parameters»):
Template:Keypressinstructions
def foo(«parameters»):
Template:Keypressinstructions
Template:Keypressreturn value
Template:N/a
S-Lang foo(«parameters» «;qualifiers») define foo («parameters») { instructions } define foo («parameters») { instructions ... return value; } public define slsh_main () { instructions }
Fortran foo («arguments»)
CALL sub_foo («arguments»)
Template:Ref
SUBROUTINE sub_foo («arguments»)Template:Indentinstructions
END SUBROUTINE
Template:Ref
type FUNCTION foo («arguments»)Template:IndentinstructionsTemplate:Indent...Template:Indentfoo = value
END FUNCTION
Template:Ref
PROGRAM mainTemplate:Indentinstructions
END PROGRAM
Forth «parameters» FOO : FOO « stack effect comment: ( before -- ) »Template:Indentinstructions
;
: FOO « stack effect comment: ( before -- after ) »Template:Indentinstructions
;
Template:N/a
PHP foo(«parameters») function foo(«parameters») { instructions } function foo(«parameters») { instructions ... return value; } rowspan=4 Template:N/a
Perl foo(«parameters»)
or
&foo«(parameters
sub foo { «my (parameters) = @_;» instructions } sub foo { «my (parameters) = @_;» instructions... «return» value; }
Raku foo(«parameters»)
or
&foo«(parameters
«multi »sub foo(parameters) { instructions } «our «type» »«multi »sub foo(parameters) { instructions ... «return» value; }
Ruby foo«(parameters def foo«(parametersTemplate:Indentinstructions
end
def foo«(parametersTemplate:IndentinstructionsTemplate:Indent«return» value
end
Rust foo(«parameters») fn foo(«parameters») { instructions } fn foo(«parameters») -> type { instructions } fn main() { instructions }
Scala foo«(parameters def foo«(parameters)»«: Unit =» { instructions } def foo«(parameters)»«: type» = { instructions ... «return» value } def main(args: Array[String]) { instructions }
Windows PowerShell foo «parameters» function foo { instructions };
or
function foo { «param(parametersinstructions }
function foo «(parameters)» { instructions ... return value };
or
function foo { «param(parametersinstructions ... return value }
rowspan=4 Template:N/a
Bash shell foo «parameters» function foo {Template:Indentinstructions
}

or
foo () {Template:Indentinstructions
}
function foo {Template:IndentinstructionsTemplate:Indentreturn «exit_code»
}

or
foo () { Template:IndentinstructionsTemplate:Indentreturn «exit_code»
}
  • parameters
    • $n ($1, $2, $3, ...)
    • $@ (all parameters)
    • $# (the number of parameters)
    • $0 (this function name)
OCaml foo parameters let «rec» foo parameters = instructions let «rec» foo parameters = instructions... return_value
F# [<EntryPoint>] let main args = instructions
Standard ML fun foo parameters = ( instructions ) fun foo parameters = ( instructions... return_value )
Haskell foo parameters = do
Template:Keypressinstructions
foo parameters = return_value
or
foo parameters = do
Template:Keypressinstructions
Template:Keypressreturn value
«main :: IO ()»
main = do instructions
Eiffel foo («parameters») foo («parameters»)Template:IndentrequireTemplate:IndentpreconditionsTemplate:IndentdoTemplate:IndentinstructionsTemplate:IndentensureTemplate:IndentpostconditionsTemplate:Indentend foo («parameters»): typeTemplate:IndentrequireTemplate:IndentpreconditionsTemplate:IndentdoTemplate:IndentinstructionsTemplate:IndentResult := valueTemplate:IndentensureTemplate:IndentpostconditionsTemplate:Indentend Template:Ref
CoffeeScript foo() foo = -> foo = -> value rowspan=2 Template:N/a
foo parameters foo = () -> foo = ( parameters ) -> value
COBOL CALL "foo" «USING parameters»Template:Indent«exception-handling»
«
END-CALL»
Template:Ref
«IDENTIFICATION DIVISION.»
PROGRAM-ID. foo.
«other divisions...»
PROCEDURE DIVISION «USING parameters».Template:Indentinstructions.
«IDENTIFICATION DIVISION.»
PROGRAM-ID/FUNCTION-ID. foo.
«other divisions...»
DATA DIVISION.
«other sections...»
LINKAGE SECTION.
«parameter definitions...»
variable-to-return definition
«other sections...»
PROCEDURE DIVISION «USING parameters» RETURNING variable-to-return.Template:Indentinstructions.
rowspan=2 Template:N/a
«FUNCTION» foo«(«parameters»)» Template:N/a
  • Template:Note Pascal requires "forward;" for forward declarations.
  • Template:Note Eiffel allows the specification of an application's root class and feature.
  • Template:Note In Fortran, function/subroutine parameters are called arguments (since PARAMETER is a language keyword); the CALL keyword is required for subroutines.
  • Template:Note Instead of using "foo", a string variable may be used instead containing the same value.

Where string is a signed decimal number:

string to integer string to long integer string to floating point integer to string floating point to string
Ada[1] Integer'Value (string_expression) Long_Integer'Value (string_expression) Float'Value (string_expression) Integer'Image (integer_expression) Float'Image (float_expression)
ALGOL 68 with general, and then specific formats With prior declarations and association of: string buf := "12345678.9012e34 "; file proxy; associate(proxy, buf);
get(proxy, ivar); get(proxy, livar); get(proxy, rvar); put(proxy, ival); put(proxy, rval);
getf(proxy, ($g$, ivar));
or
getf(proxy, ($dddd$, ivar));
getf(proxy, ($g$, livar));
or
getf(proxy, ($8d$, livar));
getf(proxy, ($g$, rvar));
or
getf(proxy, ($8d.4dE2d$, rvar));
putf(proxy, ($g$, ival));
or
putf(proxy, ($4d$, ival));
putf(proxy, ($g(width, places, exp)$, rval));
or
putf(proxy, ($8d.4dE2d$, rval));
APL string_expression string_expression string_expression integer_expression float_expression
C (C99) integer = atoi(string); long = atol(string); float = atof(string); sprintf(string, "%i", integer); sprintf(string, "%f", float);
Objective-C integer = [string intValue]; long = [string longLongValue]; float = [string doubleValue]; string = [NSString stringWithFormat:@"%i", integer]; string = [NSString stringWithFormat:@"%f", float];
C++ (STL) «std::»istringstream(string) >> number; «std::»ostringstream o; o << number; string = o.str();
C++11 integer = «std::»stoi(string); long = «std::»stol(string); float = «std::»stof(string); double = «std::»stod(string); string = «std::»to_string(number);
C# integer = int.Parse(string); long = long.Parse(string); float = float.Parse(string);double = double.Parse(string); string = number.ToString();
D integer = std.conv.to!int(string) long = std.conv.to!long(string) float = std.conv.to!float(string)
double = std.conv.to!double(string)
string = std.conv.to!string(number)
Java integer = Integer.parseInt(string); long = Long.parseLong(string); float = Float.parseFloat(string);
double = Double.parseDouble(string);
string = Integer.toString(integer);
string = String.valueOf(integer);
string = Float.toString(float);
string = Double.toString(double);
JavaScriptTemplate:Ref integer = parseInt(string); float = parseFloat(string);
float = new Number (string);
float = Number (string);
float = +string;
string = number.toString ();
string = String (number);
string = number+"";
string = `${number}`
Go integer, error = strconv.Atoi(string)
integer, error = strconv.ParseInt(string, 10, 0)
long, error = strconv.ParseInt(string, 10, 64) float, error = strconv.ParseFloat(string, 64) string = strconv.Itoa(integer)
string = strconv.FormatInt(integer, 10)
string = fmt.Sprint(integer)
string = strconv.FormatFloat(float)
string = fmt.Sprint(float)
RustTemplate:Ref string.parse::<i32>()
i32::from_str(string)
string.parse::<i64>()
i64::from_str(string)
string.parse::<f64>()
f64::from_str(string)
integer.to_string() float.to_string()
Common Lisp (setf integer (parse-integer string)) (setf float (read-from-string string)) (setf string (princ-to-string number))
Scheme (define number (string->number string)) (define string (number->string number))
ISLISP (setf integer (convert string <integer>)) (setf float (convert string <float>)) (setf string (convert number <string>))
Pascal integer := StrToInt(string); float := StrToFloat(string); string := IntToStr(integer); string := FloatToStr(float);
Visual Basic integer = CInt(string) long = CLng(string) float = CSng(string)
double = CDbl(string)
string = CStr(number)
Visual Basic .NET
(can use both VB syntax above and .NET methods shown right)
integer = Integer.Parse(string) long = Long.Parse(string) float = Single.Parse(string)
double = Double.Parse(string)
string = number.ToString()
Xojo integer = Val(string) long = Val(string) double = Val(string)
double = CDbl(string)
string = CStr(number)
or
string = Str(number)
Python integer = int(string) long = long(string) float = float(string) string = str(number)
S-Lang integer = atoi(string); long = atol(string); float = atof(string); string = string(number);
Fortran READ(string,format) number WRITE(string,format) number
PHP integer = intval(string);
or
integer = (int)string;
float = floatval(string);
float = (float)string;
string = "$number";
or
string = strval(number);
or
string = (string)number;
PerlTemplate:Ref number = 0 + string; string = "number";
Raku number = +string; string = ~number;
Ruby integer = string.to_i
or
integer = Integer(string)
float = string.to_f
float = Float(string)
string = number.to_s
Scala integer = string.toInt long = string.toLong float = string.toFloatdouble = string.toDouble string = number.toString
Smalltalk integer := Integer readFrom: string float := Float readFrom: string string := number asString
Windows PowerShell integer = [int]string long = [long]string float = [float]string string = [string]number;
or
string = "number";
or
string = (number).ToString()
OCaml let integer = int_of_string string let float = float_of_string string let string = string_of_int integer let string = string_of_float float
F# let integer = int string let integer = int64 string let float = float string let string = string number
Standard ML val integer = Int.fromString string val float = Real.fromString string val string = Int.toString integer val string = Real.toString float
Haskell (GHC) number = read string string = show number
COBOL MOVE «FUNCTION» NUMVAL(string)Template:Ref TO number MOVE number TO numeric-edited
read from write to
stdin stdout stderr
Ada[1] Get (x) Put (x) Put (Standard_Error, x)
ALGOL 68 readf(($format$, x));
or
getf(stand in, ($format$, x));
printf(($format$, x));
or
putf(stand out, ($format$, x));
putf(stand error, ($format$, x));Template:Ref
APL x← ⎕←x ⍞←x
C (C99) scanf(format, &x);
or
fscanf(stdin, format, &x);Template:Ref
printf(format, x);
or
fprintf(stdout, format, x);Template:Ref
fprintf(stderr, format, x);Template:Ref
Objective-C data = [[NSFileHandle fileHandleWithStandardInput] readDataToEndOfFile]; [[NSFileHandle fileHandleWithStandardOutput] writeData:data]; [[NSFileHandle fileHandleWithStandardError] writeData:data];
C++ «std::»cin >> x;
or
«std::»getline(«std::»cin, str);
«std::»cout << x; «std::»cerr << x;
or
«std::»clog << x;
C# x = Console.Read();
or
x = Console.ReadLine();
Console.Write(«format, »x);
or
Console.WriteLine(«format, »x);
Console.Error.Write(«format, »x);
or
Console.Error.WriteLine(«format, »x);
D x = std.stdio.readln() std.stdio.write(x)
or
std.stdio.writeln(x)
or
std.stdio.writef(format, x)
or
std.stdio.writefln(format, x)
stderr.write(x)
or
stderr.writeln(x)
or
std.stdio.writef(stderr, format, x)
or
std.stdio.writefln(stderr, format, x)
Java x = System.in.read();
or
x = new Scanner(System.in).nextInt();
or
x = new Scanner(System.in).nextLine();
System.out.print(x);
or
System.out.printf(format, x);
or
System.out.println(x);
System.err.print(x);
or
System.err.printf(format, x);
or
System.err.println(x);
Go fmt.Scan(&x)
or
fmt.Scanf(format, &x)
or
x = bufio.NewReader(os.Stdin).ReadString('\n')
fmt.Println(x)
or
fmt.Printf(format, x)
fmt.Fprintln(osTemplate:Not a typoStderr, x)
or
fmt.Fprintf(osTemplate:Not a typoStderr, format, x)
Swift x = readLine() (2.x) print(x) (2.x)
println(x) (1.x)
JavaScript
Web Browser implementation
document.write(x)
JavaScript
Active Server Pages
Response.Write(x)
JavaScript
Windows Script Host
x = WScript.StdIn.Read(chars)
or
x = WScript.StdIn.ReadLine()
WScript.Echo(x)
or
WScript.StdOut.Write(x)
or
WScript.StdOut.WriteLine(x)
WScript.StdErr.Write(x)
or
WScript.StdErr.WriteLine(x)
Common Lisp (setf x (read-line)) (princ x)
or
(format t format x)
(princ x *error-output*)
or
Template:Codett format x)
Scheme (R6RS) (define x (read-line)) (display x)
or
Template:Codett format x)
(display x (current-error-port))
or
Template:Codett format x)
ISLISP (setf x (read-line)) Template:Codett format x) Template:Codett format x)
Pascal read(x);
or
readln(x);
write(x);
or
writeln(x);
write(stderr, x);
or
writeln(stderr, x);
Visual Basic Input« promptx Print x
or
? x
Template:N/a
Visual Basic .NET x = Console.Read()
or
x = Console.ReadLine()
Console.Write(«formatx)
or
Console.WriteLine(«format, »x)
Console.Error.Write(«format, »x)
or
Console.Error.WriteLine(«format, »x)
Xojo x = StandardInputStream.Read()
or
x = StandardInputStreame.ReadLine()
StandardOutputStream.Write(x)
or
StandardOutputStream.WriteLine(x)
StdErr.Write(x)
or
StdErr.WriteLine(x)
Python 2.x x = raw_input(«prompt») print x
or
sys.stdout.write(x)
Template:Codett x
or
sys.stderr.write(x)
Python 3.x x = input(«prompt») print(, end=""») print(, end=""», file=sys.stderr)
S-Lang fgets (&x, stdin) fputs (x, stdout) fputs (x, stderr)
Fortran READ(*,format) variable names
or
READ(INPUT_UNIT,format) variable namesTemplate:Ref
WRITE(*,format) expressions
or
WRITE(OUTPUT_UNIT,format) expressionsTemplate:Ref
WRITE(ERROR_UNIT,format) expressionsTemplate:Ref
Forth buffer length ACCEPT ( # chars read )
KEY ( char )
buffer length TYPE
char EMIT
Template:N/a
PHP $x = fgets(STDIN);
or
$x = fscanf(STDIN, format);
print x;
or
echo x;
or
printf(format, x);
fprintf(STDERR, format, x);
Perl $x = <>;
or
$x = <STDIN>;
print x;
or
printf format, x;
print STDERR x;
or
printf STDERR format, x;
Raku $x = $*IN.get; x.print
or
x.say
x.note
or
$*ERR.print(x)
or
$*ERR.say(x)
Ruby x = gets puts x
or
printf(format, x)
$stderr.puts(x)
or
$stderr.printf(format, x)
Windows PowerShell $x = Read-Host«« -Prompt» text»;
or
$x = [Console]::Read();
or
$x = [Console]::ReadLine()
x;
or
Write-Output x;
or
echo x
Write-Error x
OCaml let x = read_int ()
or
let str = read_line ()
or
Scanf.scanf format (fun x ... -> ...)
print_int x
or
print_endline str
or
Printf.printf format x ...
prerr_int x
or
prerr_endline str
or
Printf.eprintf format x ...
F# let x = System.Console.ReadLine() printf format x ...
or
printfn format x ...
eprintf format x ...
or
eprintfn format x ...
Standard ML val str = TextIO.inputLIne TextIO.stdIn print str Template:Codett str)
Haskell (GHC) x <- readLn
or
str <- getLine
print x
or
putStrLn str
hPrint stderr x
or
hPutStrLn stderr str
COBOL ACCEPT x DISPLAY x
Argument values Argument counts Program name / Script name
Ada[1] Argument (n) Argument_Count Command_Name
C (C99) argv[n] argc first argument
Objective-C
C++
C# args[n] args.Length Assembly.GetEntryAssembly().Location;
Java args.length
D first argument
JavaScript
Windows Script Host implementation
WScript.Arguments(n) WScript.Arguments.length WScript.ScriptName
or
WScript.ScriptFullName
Go os.Args[n] len(os.Args) first argument
RustTemplate:Ref std::env::args().nth(n)
std::env::args_os().nth(n)
std::env::args().count()
std::env::args_os().count()
std::env::args().next()
std::env::args_os().next()
Swift Process.arguments[n] or
Process.unsafeArgv[n]
Process.arguments.count or
Process.argc
first argument
Common Lisp Template:Dunno Template:Dunno Template:Dunno
Scheme (R6RS) (list-ref (command-line) n) (length (command-line)) first argument
ISLISP Template:N/a Template:N/a Template:N/a
Pascal ParamStr(n) ParamCount first argument
Visual Basic CommandTemplate:Ref Template:N/a App.Path
Visual Basic .NET CmdArgs(n) CmdArgs.Length [Assembly].GetEntryAssembly().Location
Xojo System.CommandLine (string parsing) Application.ExecutableFile.Name
Python sys.argv[n] len(sys.argv) first argument
S-Lang __argv[n] __argc first argument
Fortran DO i = 1,argcTemplate:IndentCALL GET_COMMAND_ARGUMENT (i,argv(i))
ENDDO
argc = COMMAND_ARGUMENT_COUNT () CALL GET_COMMAND_ARGUMENT (0,progname)
PHP $argv[n] $argc first argument
Bash shell $n ($1, $2, $3, ...)
$@ (all arguments)
$# $0
Perl $ARGV[n] scalar(@ARGV) $0
Raku @*ARGS[n] @*ARGS.elems $PROGRAM_NAME
Ruby ARGV[n] ARGV.size $0
Windows PowerShell $args[n] $args.Length $MyInvocation.MyCommand.Name
OCaml Sys.argv.(n) Array.length Sys.argv first argument
F# args.[n] args.Length Assembly.GetEntryAssembly().Location
Standard ML Template:Code Template:Code Template:Code
Haskell (GHC) Template:Code} Template:Code} System.getProgName
COBOL Template:Ref Template:N/a
  • Template:Note In Rust, std::env::args and std::env::args_os return iterators, std::env::Args and std::env::ArgsOs respectively. Args converts each argument to a String and it panics if it reaches an argument that cannot be converted to UTF-8. ArgsOs returns a non-lossy representation of the raw strings from the operating system (std::ffi::OsString), which can be invalid UTF-8.
  • Template:Note In Visual Basic, command-line arguments are not separated. Separating them requires a split function Split(string).
  • Template:Note The COBOL standard includes no means to access command-line arguments, but common compiler extensions to access them include defining parameters for the main program or using ACCEPT statements.

Execution of commands

Shell command Execute program Replace current program with new executed program
Ada[1] Not part of the language standard. Commonly done by compiler provided packages or by interfacing to C or POSIX.[16]
C system("command"); execl(path, args);
or
execv(path, arglist);
C++
Objective-C [NSTask launchedTaskWithLaunchPath:(NSString *)path arguments:(NSArray *)arguments];
C# System.Diagnostics.Process.Start(path, argstring);
F#
Go exec.Run(path, argv, envv, dir, exec.DevNull, exec.DevNull, exec.DevNull) os.Exec(path, argv, envv)
Visual Basic Interaction.Shell(command «, WindowStyle» «, isWaitOnReturn»)
Visual Basic .NET Microsoft.VisualBasic.Interaction.Shell(command «, WindowStyle» «, isWaitOnReturn») System.Diagnostics.Process.Start(path, argstring)
Xojo Shell.Execute(command «, Parameters») FolderItem.Launch(parameters, activate) Template:N/a
D std.process.system("command"); std.process.execv(path, arglist);
Java Runtime.exec(command);
or
new ProcessBuilder(command).start();
JavaScript
Windows Script Host implementation
Template:Codettcommand «, WindowStyle» «, isWaitOnReturn»); WshShell.Exec(command)
Common Lisp (uiop:run-program command)
Scheme (system command)
ISLISP Template:N/a Template:N/a Template:N/a
Pascal system(command);
OCaml Sys.command command, Unix.open_process_full command env (stdout, stdin, stderr),... Unix.create_process prog args new_stdin new_stdout new_stderr, ... Unix.execv prog args
or
Unix.execve prog args env
Standard ML OS.Process.system command Unix.execute (path, args) Posix.Process.exec (path, args)
Haskell (GHC) System.system command System.Process.runProcess path args ... Posix.Process.executeFile path True args ...
Perl system(command)
or
$output = `command`
or
$output = qx(command)
exec(path, args)
Ruby system(command)
or
output = `command`
exec(path, args)
PHP system(command)
or
$output = `command`
or
exec(command)
or
passthru(command)
Python os.system(command)
or
subprocess.Popen(command)
subprocess.call(["program", "arg1", "arg2", ...]) os.execv(path, args)
S-Lang system(command)
Fortran CALL EXECUTE_COMMAND_LINE (COMMAND «, WAIT» «, EXITSTAT» «, CMDSTAT» «, CMDMSG»)Template:Ref
Windows PowerShell [Diagnostics.Process]::Start(command) «Invoke-Item »program arg1 arg2 ...
Bash shell output=`command`
or
output=$(command)
program arg1 arg2 ...

Template:Note Fortran 2008 or newer.[17]

References

Template:Reflist