Menu
Home Explore People Places Arts History Plants & Animals Science Life & Culture Technology
On this page
Comparison of programming languages (basic instructions)
List article

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, var, or var is how variable names or other non-literal values to be interpreted by the reader are represented. The rest is literal code. Guillemets (« and ») enclose optional sections. Tab ↹ 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.

Type identifiers

Integers

8 bit (byte)16 bit (short integer)32 bit64 bit (long integer)Word sizeArbitrarily precise (bignum)
SignedUnsignedSignedUnsignedSignedUnsignedSignedUnsignedSignedUnsigned
Ada1range -2**7 .. 2**7 - 1[j]range 0 .. 2**8 - 1[j] or mod 2**8[k]range -2**15 .. 2**15 - 1[j]range 0 .. 2**16 - 1[j] or mod 2**16[k]range -2**31 .. 2**31 - 1[j]range 0 .. 2**32 - 1[j] or mod 2**32[k]range -2**63 .. 2**63 - 1[j]mod 2**64[k]Integer[j]range 0 .. 2**Integer'Size - 1[j] or mod Integer'Size[k]
ALGOL 68 (variable-width)short short int[c]short int[c]int[c]long int[c]int[c]long long int[a][g]
bytes and bits
C (C99 fixed-width)int8_tuint8_tint16_tuint16_tint32_tuint32_tint64_tuint64_tintptr_t[c]size_t[c]
C++ (C++11 fixed-width)
C (C99 variable-width)signed charunsigned charshort[c]unsigned short[c]long[c]unsigned long[c]long long[c]unsigned long long[c]int[c]unsigned int[c]
C++ (C++11 variable-width)
Objective-C (Cocoa)signed char or int8_tunsigned char or uint8_tshort or int16_tunsigned short or uint16_tint or int32_tunsigned int or uint32_tlong long or int64_tunsigned long long or uint64_tNSInteger or longNSUInteger or unsigned long
C#sbytebyteshortushortintuintlongulongIntPtrUIntPtrSystem.Numerics.BigInteger(.NET 4.0)
Javabytechar[b]java.math.BigInteger
Goint8uint8 or byteint16uint16int32uint32int64uint64intuintbig.Int
Rusti8u8i16u16i32u32i64u64isizeusize
SwiftInt8UInt8Int16UInt16Int32UInt32Int64UInt64IntUInt
DbyteubyteshortushortintuintlongulongBigInt
Common Lisp2(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
ISLISP3bignum
Pascal (FPC)shortintbytesmallintwordlongintlongwordint64qwordintegercardinal
Visual BasicByteIntegerLong
Visual Basic .NETSByteShortUShortIntegerUIntegerLongULongSystem.Numerics.BigInteger(.NET 4.0)
FreeBasicByte 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>IntegerUInteger
Python 2.xintlong
Python 3.xint
S-Lang
FortranINTEGER(KIND = n)[f]INTEGER(KIND = n)[f]INTEGER(KIND = n)[f]INTEGER(KIND = n)[f]
PHPint[m]int[m][e]
Perl 5—[d]—[d]—[d]—[d]—[d]Math::BigInt
Rakuint8uint8int16uint16int32uint32int64uint64Int
RubyFixnumBignum
Erlang[n]integer()integer()[o]
ScalaByteShortChar[l]IntLongscala.math.BigInt
Seed7integerbigInteger
SmalltalkSmallInteger[i]LargeInteger[i]
Windows PowerShell
OCamlint32int64int or nativeintopen Big_int;; or big_int
F#sbytebyteint16uint16int32 or intuint32uint64nativeintunativeintbigint
Standard MLWord8.wordInt32.intWord32.wordInt64.intWord64.wordintwordLargeInt.int orIntInf.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 Word64Int«import Word» or WordInteger
EiffelINTEGER_8NATURAL_8INTEGER_16NATURAL_16INTEGER_32NATURAL_32INTEGER_64NATURAL_64INTEGERNATURAL
COBOL[h]BINARY-CHAR «SIGNED»BINARY-CHAR UNSIGNEDBINARY-SHORT «SIGNED»BINARY-SHORT UNSIGNEDBINARY-LONG «SIGNED»BINARY-LONG UNSIGNEDBINARY-DOUBLE «SIGNED»BINARY-DOUBLE UNSIGNED
MathematicaInteger
Wolfram LanguageInteger
  • ^a 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.
  • ^b Commonly used for characters.
  • ^c 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++11 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.
  • ^d Perl 5 does not have distinct types. Integers, floating point numbers, strings, etc. are all considered "scalars".
  • ^e PHP has two arbitrary-precision libraries. The BCMath library just uses strings as datatype. The GMP library uses an internal "resource" type.
  • ^f The value of n is provided by the SELECTED_INT_KIND4 intrinsic function.
  • ^g 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.
  • ^h 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.
  • ^i 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 (SmallInteger) and one supporting arbitrary sized integers (LargeInteger). Arithmetic operations support polymorphic arguments and return the result in the most appropriate compact representation.
  • ^j 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.
  • ^k Ada modulo types implement modulo arithmetic in all operations, i.e. no range violations are possible. Modulos are not restricted to powers of two.
  • ^l Commonly used for characters like Java's char.
  • ^m int in PHP has the same width as long type in C has on that system.[c]
  • ^n 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
  • ^o When it exceeds one word.6

Floating point

Single precisionDouble precisionOther precisionProcessor dependent
Ada7FloatLong_Float
ALGOL 68real[a]long real[a]short real, long long real, etc.[d]
Cfloat[b]doublelong double[f]
C++ (STL)
Objective-C (Cocoa)CGFloat
C#float
Java
Gofloat32float64
Rustf32f64f16, f128
SwiftFloat or Float32Double or Float64Float80[g]CGFloat
Dfloatdoublereal
Common Lispsingle-floatdouble-floatfloat, short-float, long-float
Scheme
ISLISP
Pascal (FPC)singledoublereal
Visual BasicSingleDouble
Visual Basic .NET
Xojo
Pythonfloat
JavaScriptNumber8
S-Lang
FortranREAL(KIND = n)[c]
PHPfloat
Perl
Rakunum32num64Num
RubyFloat
ScalaFloatDouble
Seed7float
SmalltalkFloatDouble
Windows PowerShell
OCamlfloat
F#float32
Standard MLreal
Haskell (GHC)FloatDouble
EiffelREAL_32REAL_64
COBOLFLOAT-BINARY-7[e]FLOAT-BINARY-34[e]FLOAT-SHORT, FLOAT-LONG, FLOAT-EXTENDED
MathematicaReal
  • ^a 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.
  • ^b declarations of single precision often are not honored
  • ^c The value of n is provided by the SELECTED_REAL_KIND9 intrinsic function.
  • ^d 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.
  • ^e These IEEE floating-point types will be introduced in the next COBOL standard.
  • ^f Same size as double on many implementations.
  • ^g Swift supports 80-bit extended precision floating point type, equivalent to long double in C languages.

Complex numbers

IntegerSingle precisionDouble precisionHalf and Quadruple precision etc.
Ada10Complex[b]Complex[b]Complex[b]
ALGOL 68compllong compl etc.short compl etc. and long long compl etc.
C (C99)11float complexdouble complex
C++ (STL)std::complex<float>std::complex<double>
C#System.Numerics.Complex(.NET 4.0)
Java
Gocomplex64complex128
Dcfloatcdouble
Objective-C
Common Lisp(complex integer)(complex single-float)(complex double-float)complex
Scheme
Pascal
Visual Basic
Visual Basic .NETSystem.Numerics.Complex(.NET 4.0)
PerlMath::Complex
Rakucomplex64complex128Complex
Pythoncomplex
JavaScript
S-Lang
FortranCOMPLEX(KIND = n)[a]
RubyComplexComplex
Scala
Seed7complex
SmalltalkComplexComplexComplex
Windows PowerShell
OCamlComplex.t
F#System.Numerics.Complex(.NET 4.0)
Standard ML
Haskell (GHC)Complex.Complex FloatComplex.Complex Double
Eiffel
COBOL
MathematicaComplexComplex
  • ^a The value of n is provided by the SELECTED_REAL_KIND12 intrinsic function.
  • ^b Generic type which can be instantiated with any base floating point type.

Other variable types

TextBooleanEnumerationObject/Universal
CharacterString[a]
Ada13CharacterString, Bounded_String, Unbounded_StringBoolean(item1, item2, ...)tagged null record
ALGOL 68charstring, bytesbool, bits— - User defined
C (C99)char, wchar_tbool[b]enum «name» { item1, item2, ... };void *
C++ (STL)«std::»string
Objective-CunicharNSString *BOOLid
C#charstringboolenum name { item1« = value», item2« = value», ... }object
JavaStringbooleanenum name { item1, item2, ... }Object
Gobyte, runestringboolconst (   item1 = iota   item2   ...)interface{}
RustcharStringboolenum name { item1« = value», item2« = value», ... }std::any::Any
SwiftCharacterStringBoolenum name { case item1, item2, ... }Any
Dcharstringboolenum name { item1, item2, ... }std.variant.Variant
Common Lispcharacterstringboolean(member item1 item2 ...)t
Scheme
ISLISP
Pascal (ISO)charboolean( item1, item2, ... )
Object Pascal (Delphi)stringvariant
Visual BasicStringBooleanEnum name   item1 «= value»   item2 «= value»   ...End Enum[[Variant type|Variant]]
Visual Basic .NETCharObject
XojoObject or Variant
Python—[d]strboolfrom enum import Enumclass Name(Enum):   item1 = value   item2 = value   ...object
JavaScript—[d]StringBooleanObject
S-Lang
FortranCHARACTER(LEN = *)CHARACTER(LEN = :), allocatableLOGICAL(KIND = n)[f]CLASS(*)
PHP—[d]stringbool(type declaration omitted)
Perl—[d]UNIVERSAL
RakuCharStrBoolenum name<item1 item2 ...>enum name <<:item1(value) :item2(value) ..>>Mu
Ruby—[d]StringObject[c]Object
ScalaCharStringBooleanobject name extends Enumeration {   val item1, item2, ... = Value}Any
Seed7charstringbooleanconst type: name is new enum   item1,   item2,   ...end enum;
Windows PowerShell
OCamlcharstringbool—[e]
F#type name = item1 = value |item2 = value | ...obj
Standard ML—[e]
Haskell (GHC)CharStringBool—[e]
EiffelCHARACTERSTRINGBOOLEANANY
COBOLPIC XPIC X(string length) or PIC X«X...»PIC 1«(number of digits or PIC 1«1...»OBJECT REFERENCE
Mathematica—[d]String
  • ^a specifically, strings of arbitrary length and automatically managed.
  • ^b This language represents a boolean as an integer where false is represented as a value of zero and true by a non-zero value.
  • ^c All values evaluate to either true or false. Everything in TrueClass evaluates to true and everything in FalseClass evaluates to false.
  • ^d This language does not have a separate character type. Characters are represented as strings of length 1.
  • ^e Enumerations in this language are algebraic types with only nullary constructors
  • ^f The value of n is provided by the SELECTED_INT_KIND14 intrinsic function.

Derived types

Array

Further information: Comparison of programming languages (array)

fixed size arraydynamic size array
one-dimensional arraymultidimensional arrayone-dimensional arraymultidimensional array
Ada15array (<first> .. <last>) of <type>orarray (<discrete_type>) of <type>array (<first1> .. <last1>, <first2> .. <last2>, ...) of <type>orarray (<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»orflex[first1:last1]flex[first2:last2]«modename» etc.
C (C99)type name[size][a]type name[size1][size2][a]type *nameor within a block:int n = ...; type name[n]
C++ (STL)«std::»array<type, size>(C++11)«std::»vector<type>
C#type[]type[,,...]System.Collections.ArrayListorSystem.Collections.Generic.List<type>
Javatype[][b]type[][]...[b]ArrayList or ArrayList<type>
Dtype[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-CNSArrayNSMutableArray
JavaScriptArray[d]
Common Lisp(simple-array type (dimension))(simple-array type (dimension1 dimension2))(array type (dimension))(array type (dimension1 dimension2))
Scheme
ISLISP
Pascalarray[first..last] of type[c]array[first1..last1] of array[first2..last2] ... of type[c]or array[first1..last1, first2..last2, ...] of type[c]
Object Pascal (Delphi)array of typearray of array ... of type
Visual BasicDim x(last) As typeDim x(last1, last2,...) As type
Visual Basic .NETtype()type(,,...)System.Collections.ArrayListorSystem.Collections.Generic.List(Of type)
Pythonlist
S-Langx = type[size];x = type[size1, size2, ...];
Fortrantype :: name(size)type :: name(size1, size2,...)type, ALLOCATABLE :: name(:)type, ALLOCATABLE :: name(:,:,...)
PHParray
Perl
RakuArray[type] or Array of type
Rubyx = Array.new(size1){ Array.new(size2) }Array
ScalaArray[type]Array[...[Array[type]]...]ArrayBuffer[type]
Seed7array typeorarray [idxType] typearray array typeorarray [idxType] array [idxType] typearray typeorarray [idxType] typearray array typeorarray [idxType] array [idxType] type
SmalltalkArrayOrderedCollection
Windows PowerShelltype[]type[,,...]
OCamltype arraytype array ... array
F#type []ortype arraytype [,,...]System.Collections.ArrayListorSystem.Collections.Generic.List<type>
Standard MLtype vector or type array
Haskell (GHC)x = Array.array (0, size-1) list_of_association_pairsx = Array.array ((0, 0,...), (size1-1, size2-1,...)) list_of_association_pairs
COBOLlevel-number type OCCURS size «TIMES».one-dimensional array definition...level-number type OCCURS min-size TO max-size «TIMES» DEPENDING «ON» size.[e]
  • ^a In 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.
  • ^b The C-like type x[] works in Java, however type[] x is the preferred form of array declaration.
  • ^c Subranges are used to define the bounds of the array.
  • ^d JavaScript's array are a special kind of object.
  • ^e 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 typesAlgebraic data typesUnions
RecordsTuple expression
Ada16type name is «abstract» «tagged» «limited» [record  field1 : type;  field2 : type;  ...end record | null record]Any combination of records, unions, and enumerations (as well as references to those, enabling recursive types).type name (variation : discrete_type) is record  case variation is     when choice_list1 =>      fieldname1 : type;      ...     when choice_list2 =>      fieldname2 : type;      ...     ...  end case;end record
ALGOL 68struct (modename «fieldname», ...);Required types and operators can be user-definedunion (modename, ...);
C (C99)struct «name» {type name;...};union {type name;...};
Objective-C
C++struct «name» {type name;...};[b]«std::»tuple<type1..typen>
C#struct name {type name;...}(val1, val2, ... )
Java—[a]
JavaScript
Dstruct name {type name;...}std.variant.Algebraic!(type,...)union {type name;...}
Gostruct {   «name» type  ...}
Ruststruct name {name: type, ...}(val1, val2, ... )enum name { Foo(types), ...}union name {name: type, ...}
Swiftstruct name {  var name «: type»  ...}(«name1:» val1, «name2:» val2, «name3:» val3, ... )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 val1 val2)[c]
Scheme
ISLISP
Pascalrecord  name: type;  ...endrecord  case type of  value: (types);  ...end
Visual Basic
Visual Basic .NETStructure name  Dim name As type  ...End Structure(val1, val2, ... )
Python—[a]«(»val1, val2, val3, ... «)»
S-Langstruct {name [=value], ...}
FortranTYPE name  type :: name  ...END TYPE
PHP—[a]
Perl—[d]
Raku—[a]
RubyOpenStruct.new({:name => value})
Scalacase class namevar» name: type, ...)(val1, val2, val3, ... )abstract class name  case class Fooparameters») extends name  case class Barparameters») extends name  ...orabstract class name  case object Foo extends name  case object Bar extends name  ...or a combination of case classes and case objects
Windows PowerShell
OCamltype name = {«mutable» name : type;...}«(»val1, val2, val3, ... «)»type name = Foo «of type» | Bar «of type» | ...
F#
Standard MLtype name = {name : type,...}(val1, val2, val3, ... )datatype name = Foo «of type» | Bar «of type» | ...
Haskelldata Name = Constr {name :: type,...}data Name = Foo «types» | Bar «types» | ...
COBOLlevel-number name type clauses.  level-number+n name type clauses.  ...name REDEFINES variable type.
  • ^a Only classes are supported.
  • ^b 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.
  • ^c pair only
  • ^d 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.
  • ^e Enumerations in this language are algebraic types with only nullary constructors

Variable and constant declarations

variableconstanttype synonym
Ada17identifier : type« := initial_value»[e]identifier : constant type := final_valuesubtype identifier is type
ALGOL 68modename 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», ...;orvar name = initial_value;const type name = value, name = value, ...;orreadonly type name = value, name = value, ... ;using synonym = type;
Dtype name« = initial_value»;orauto name = value;const type name = value;orimmutable type name = value;alias type synonym;
Javatype name« = initial_value»;final type name = value;
JavaScriptvar name« = initial_value»; orlet name« = initial_value»; (since ECMAScript 2015)const name = value; (since ECMAScript 2015)
Govar name type« = initial_value»orname := initial_valueconst name «type» = valuetype synonym type
Rust[f]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;
Swiftvar name «: type»« = initial_value»let name «: type» = valuetypealias 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)
Pascal[a]name: type« = initial_value»name = valuesynonym = type
Visual BasicDim 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 typesConst name1 «As type» = value, name2 «As type» = value, ...
Visual Basic .NET18The 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     Dim 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
XojoDim name «As type»« = initial_value»
Pythonname«: type» = initial_valuesynonym = type[b]
CoffeeScriptname = initial_value
S-Langname = initial_value;typedef struct {...} typename
Fortrantype :: nametype, PARAMETER :: name = value
PHP$name = initial_value;define("name", value);const name = value (5.3+)
Perl«my» $name« = initial_value»;[c]use constant name => value;
Raku«my «type»» $name« = initial_value»;[c]«my «type»» constant name = value;::synonym ::= type
Rubyname = initial_valueName = valuesynonym = type[b]
Scalavar name«: type» = initial_valueval name«: type» = valuetype synonym = type
Windows PowerShell«[type]» $name = initial_value
Bash shellname=initial_value
OCamllet name« : type ref» = ref value[d]let name «: type» = valuetype synonym = type
F#let mutable name «: type» = value
Standard MLval name «: type ref» = ref value[d]val name «: type» = value
Haskell«name::typename = valuetype Synonym = type
ForthVARIABLE name (in some systems use value VARIABLE name instead)value CONSTANT name
COBOLlevel-number name type clauses.«0»1 name CONSTANT «AS» value.level-number name type clauses «IS» TYPEDEF.
Mathematicaname=initial_value
  • ^a Pascal has declaration blocks. See functions.
  • ^b Types are just regular objects, so you can just assign them.
  • ^c In Perl, the "my" keyword scopes the variable into the block.
  • ^d 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.
  • ^e 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.
  • ^f 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.

Control flow

Conditional statements

ifelse ifselect caseconditional expression
Ada19if condition then  statements«else  statements»end ifif condition1 then  statementselsif condition2 then  statements...«else  statements»end ifcase expression is  when value_list1 => statements  when value_list2 => statements  ...  «when others => statements»end case(if condition1 then  expression1«elsif condition2 then  expression2»...else  expressionn)or(case expression is  when value_list1 => expression1  when value_list2 => expression2  ...  «when others => expressionn»)
Seed7if condition then  statements«else  statements»end ifif condition1 then  statementselsif condition2 then  statements...«else  statements»end ifcase expression of  when set1 : statements  ...  «otherwise: statements»end case
Modula-2if condition then  statements«else  statements»endif condition1 then  statementselsif condition2 then  statements...«else  statements»endcase expression of  caseLabelList : statements |  ...  «else statements»end
ALGOL 68if condition then statements «else statements» fiif condition then statements elif condition then statements ficase 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 condition  instructions«:Else  instructions»:EndIf:If condition  instructions:ElseIf condition  instructions...«:Else  instructions»:EndIf:Select expression  :Case case1     instructions  ...  «:Else     instructions»: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) instructionselse if (condition) instructions...«else instructions»orif (condition) instructionselse { if (condition) instructions }switch (variable) {   case case1: instructions «; break;»  ...  «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) instructionselse if (condition) instructions...«else instructions»switch (variable){   case case1:     instructions     «break_or_jump_statement»  ...  «default:     instructions     break_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 PowerShellif (condition) instruction«else instructions»if (condition) { instructions }elseif (condition) { instructions }...«else { instructionsswitch (variable) { case1{instructions «break;» } ... «default { instructions }»}
Goif condition {instructions}«else {instructionsif condition {instructions}else if condition {instructions}...«else {instructions}»orswitch {   case condition: instructions  ...  «default: instructions»}switch variable {   case case1: instructions  ...  «default: instructions»}
Swiftif condition {instructions}«else {instructionsif condition {instructions}else if condition {instructions}...«else {instructionsswitch variable {   case case1: instructions  ...  «default: instructions»}
Perlif (condition) {instructions}«else {instructions}»orunless (notcondition) {instructions}«else {instructionsif (condition) {instructions}elsif (condition) {instructions}...«else {instructions}»orunless (notcondition) {instructions}elsif (condition) {instructions}...«else {instructionsuse feature "switch";...given (variable) {   when (case1) { instructions }  ...  «default { instructions }»}condition ? valueIfTrue : valueIfFalse
Rakuif condition {instructions}«else {instructions}»orunless notcondition {instructions}if condition {instructions}elsif condition {instructions}...«else {instructions}given variable {   when case1 { instructions }  ...  «default { instructions }»}condition ?? valueIfTrue !! valueIfFalse
Rubyif condition  instructions«else  instructions»if condition  instructionselsif condition  instructions...«else  instructions»endcase variable  when case1     instructions  ...  «else     instructions»endcondition ? valueIfTrue : valueIfFalse
Scalaif (condition) {instructions}«else {instructionsif (condition) {instructions}else if (condition) {instructions}...«else {instructionsexpression match {   case pattern1 => expression  case pattern2 => expression  ...  «case _ => expression»}[b]if (condition) valueIfTrue else valueIfFalse
Smalltalkcondition ifTrue:  trueBlock«ifFalse:  falseBlock»endcondition ifTrue: trueBlock ifFalse: falseBlock
Common Lisp(when condition  instructions)or(unless condition  instructions)or(if condition  (progn instructions)  «(progn instructions)»)(cond (condition1 instructions)  (condition2 instructions)  ...  «(t instructions)»)(case expression  (case1 instructions)  (case2 instructions)  ...  «(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 condition  (progn instructions)  «(progn instructions)»)(cond (condition1 instructions)  (condition2 instructions)  ...  «(t instructions)»)(case expression  (case1 instructions)  (case2 instructions)  ...  «(t instructions)»)(if condition valueIfTrue valueIfFalse)
Pascalif condition then begin  instructionsend«else begin  instructionsend»'[c]if condition then begin  instructionsendelse if condition then begin  instructionsend...«else begin  instructionsend»[c]case variable of  case1: instructions  ...  «else: instructions»end[c]
Visual BasicIf condition Then  instructions«Else  instructions»End IfSingle-line, when instructions are instruction1 : instruction2 : ...:If condition Then instructions «Else instructions»If condition Then  instructionsElseIf condition Then  instructions...«Else  instructions»End IfSingle-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» variable  Case case_pattern1     instructions  ...  «Case Else     instructions»End SelectIIf(condition, valueIfTrue, valueIfFalse)
Visual Basic .NETIf(condition, valueIfTrue, valueIfFalse)
Xojo
Python[a]if condition :Tab ↹instructions«else:Tab ↹instructions»if condition :Tab ↹instructionselif condition :Tab ↹instructions...«else:Tab ↹instructions»Python 3.10+:match variable:Tab ↹case case1:Tab ↹Tab ↹instructionsTab ↹case case2:Tab ↹Tab ↹instructionsPython 2.5+:valueIfTrue if condition else valueIfFalse
S-Langif (condition) { instructions } «else { instructionsif (condition) { instructions } else if (condition) { instructions } ... «else { instructionsswitch (variable) { case case1: instructions } { case case2: instructions } ...
FortranIF (condition) THEN  instructionsELSE  instructionsENDIFIF (condition) THEN  instructionsELSEIF (condition) THEN  instructions...ELSE  instructionsENDIFSELECT CASE(variable)  CASE (case1)     instructions  ...  CASE DEFAULT     instructionsEND SELECT
Forthcondition IF instructions « ELSE instructions» THENcondition IF instructions ELSE condition IF instructions THEN THENvalue CASE  case OF instructions ENDOF  case OF instructions ENDOF     default instructionsENDCASEcondition IF valueIfTrue ELSE valueIfFalse THEN
OCamlif 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   pattern1 -> expression  | pattern2 -> expression  ...  «| _ -> expression»[b]if condition then valueIfTrue else valueIfFalse
F#Lightweight syntax mode:

Either on a single line or with indentation as shown below:if condition thenTab ↹instructions«elseTab ↹instructions»Verbose syntax mode:Same as Standard ML.

Lightweight syntax mode:Either on a single line or with indentation as shown below:if condition thenTab ↹instructionselif condition thenTab ↹instructions...«elseTab ↹instructions»Verbose syntax mode:Same as Standard ML.
Standard MLif condition then «(»instructions «)»else «(» instructions «if condition then «(»instructions «)»else if condition then «(» instructions «...else «(» instructions «case value of  pattern1 => expression  | pattern2 => expression  ...  «| _ => expression»[b]
Haskell (GHC)if condition then expression else expressionorwhen condition (do instructions)orunless notcondition (do instructions)result | condition = expression  | condition = expression  | otherwise = expressioncase value of {   pattern1 -> expression;  pattern2 -> expression;  ...  «_ -> expression»}[b]
Bash shellif condition-command; then  expression«else  expression»fiif condition-command; then  expressionelif condition-command; then  expression«else  expression»ficase "$variable" in  "$condition1" )     command...  "$condition2" )     command...esac
CoffeeScriptif condition then expression «else expression»orif condition  expression«else  expression»orexpression if conditionorunless condition  expression«else  expression»orexpression unless conditionif condition then expression else if condition then expression «else expression»orif condition  expressionelse if condition  expression«else  expression»orunless condition  expressionelse unless condition  expression«else  expression»switch expression  when condition then expression  else expressionorswitch expression  when condition     expression  «else     expression»All conditions are expressions.
COBOLIF condition «THEN»  expression«ELSE  expression».[d]EVALUATE expression «ALSO expression...»  WHEN case-or-condition «ALSO case-or-condition...»     expression  ...  «WHEN OTHER     expression»END-EVALUATE
Rustif condition {   expression}« else {   expressionif condition {   expression} else if condition {  expression}« else {  expression}»match variable {   pattern1 => expression,  pattern2 => expression,  pattern3 => expression,  «_ => expression»}[b][e]All conditions are expressions
ifelse ifselect caseconditional expression
  • ^a 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.
  • ^b This is pattern matching and is similar to select case but not the same. It is usually used to deconstruct algebraic data types.
  • ^c In languages of the Pascal family, the semicolon is not part of the statement. It is a separator between statements, not a terminator.
  • ^d END-IF may be used instead of the period at the end.
  • ^e 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 {}).

Loop statements

while loopdo while loop(count-controlled) for loopforeach
Ada20while condition loop  statementsend looploop  statements  exit when not conditionend loopfor index in «reverse» [first .. last | discrete_type] loop  statementsend loopfor item of «reverse» iterator loop  statementsend loopor(for [all | some] [in | of] [first .. last | discrete_type | iterator] => predicate)[b]
ALGOL 68«for index» «from first» «by increment» «to last» «while condition» do statements odfor key «to upb list» do «typename val=list[key];» statements od
«while condition»  do statements od«while statements; condition»  do statements od«for index» «from first» «by increment» «to last» do statements od
APL:While condition  statements:EndWhile:Repeat  statements:Until condition:For var«s» :In list  statements:EndFor:For var«s» :InEach list  statements:EndFor
C (C99)instructions can be a single statement or a block in the form of: { statements }while (condition) instructionsdo instructions while (condition);for («type» i = first; i <= last; i++) instructions
Objective-Cfor (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
Javafor (type item : set) instructions
JavaScriptfor (var i = first; i <= last; i++) instructionsSince EcmaScript 2015:21

for (var item of set) instructions

PHPforeach (range(first, last) as $i) instructionsorfor ($i = first; $i <= last; $i++) instructionsforeach (set as item) instructionsorforeach (set as key => item) instructions
Windows PowerShellfor ($i = first; $i -le last; $i++) instructionsforeach (item in set) instructions
Dforeach (i; first ... last) instructionsforeach («type» item; set) instructions
Gofor condition { instructions }for i := first; i <= last; i++ { instructions }for key, item := range set { instructions }
Swiftwhile condition { instructions }2.x:repeat { instructions } while condition1.x:do { instructions } while conditionfor i = first ... last { instructions }orfor i = first ..< last+1 { instructions }orfor var i = first; i <= last; i++ { instructions }for item in set { instructions }
Perlwhile (condition) { instructions }oruntil (notcondition) { instructions }do { instructions } while (condition)ordo { instructions } until (notcondition)for«each» «$i» (first .. last) { instructions }orfor ($i = first; $i <= last; $i++) { instructions }for«each» «$item» (set) { instructions }
Rakuwhile condition { instructions }oruntil notcondition { instructions }repeat { instructions } while conditionorrepeat { instructions } until notconditionfor first..last -> $i { instructions }orloop ($i = first; $i <=last; $i++) { instructions }for set« -> $item» { instructions }
Rubywhile condition  instructionsendoruntil notcondition  instructionsendbegin  instructionsend while conditionorbegin  instructionsend until notconditionfor i in first..last  instructionsendorfor i in first...last+1  instructionsendorfirst.upto(last) { |i| instructions }for item in set  instructionsendorset.each { |item| instructions }
Bash shellwhile condition ;do  instructionsdoneoruntil notcondition ;do  instructionsdonefor ((i = first; i <= last; ++i)) ; do  instructionsdonefor item in set ;do  instructionsdone
Scalawhile (condition) { instructions }do { instructions } while (condition)for (i <- first to last «by 1») { instructions }orfirst to last «by 1» foreach (i => { instructions })for (item <- set) { instructions }orset foreach (item => { instructions })
SmalltalkconditionBlock whileTrue:  loopBlockloopBlock doWhile:  conditionBlockfirst to: last do:  loopBlockcollection do:  loopBlock
Common Lisp(loop  while condition  do  instructions)or(do () (notcondition)  instructions)(loop  do  instructions  while condition)(loop  for i from first to last «by 1»  do  instructions)or(dotimes (i N)  instructions)or(do ((i first (1+ i))) ((>=i last))  instructions)(loop  for item in list  do  instructions)or(loop  for item across vector  do  instructions)or(dolist (item list)  instructions)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)
Pascalwhile condition do begin  instructionsendrepeat  instructionsuntil notcondition;for i := first «step 1» to last do begin  instructionsend;[a]for item in set do instructions
Visual BasicDo While condition  instructionsLooporDo Until notcondition  instructionsLooporWhile condition  instructionsWend (Visual Basic .NET uses End While instead)Do  instructionsLoop While conditionorDo  instructionsLoop Until notconditioni must be declared beforehand.

For i = first To last «Step 1»  instructionsNext i

For Each item In set  instructionsNext item
Visual Basic .NETFor i« As type» = first To last« Step 1»  instructionsNext« i»[a]For Each item« As type» In set  instructionsNext« item»
XojoWhile condition  instructionsWendDo Until notcondition  instructionsLooporDo  instructionsLoop Until notcondition
Pythonwhile condition :Tab ↹instructions«else:Tab ↹instructions»Python 3.x:for i in range(first, last+1):Tab ↹instructions«else:Tab ↹instructions»Python 2.x:for i in xrange(first, last+1):Tab ↹instructions«else:Tab ↹instructions»for item in set:Tab ↹instructions«else:Tab ↹instructions»
S-Langwhile (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»
FortranDO WHILE (condition)  instructionsENDDODO  instructions  IF (condition) EXITENDDODO I = first,last  instructionsENDDO
ForthBEGIN «instructions» condition WHILE instructions REPEATBEGIN instructions condition UNTILlimit start DO instructions LOOP
OCamlwhile condition do instructions donefor i = first to last do instructions doneArray.iter (fun item -> instructions) arrayorList.iter (fun item -> instructions) list
F#while condition doTab ↹instructionsfor i = first to last doTab ↹instructionsforitem in set doTab ↹instructionsorSeq.iter (fun item -> instructions) set
Standard MLwhile condition do ( instructions )Array.app (fn item => instructions) arrayorapp (fn item => instructions) list
Haskell (GHC)Control.Monad.forM_ [first..last] (\i -> do instructions)Control.Monad.forM_list (\item -> do instructions)
Eiffelfrom  setupuntil  conditionloop  instructionsend
CoffeeScriptwhile condition  expressionorexpression while conditionorwhile condition then expressionoruntil condition  expressionorexpression until conditionoruntil expression then conditionfor i in [first..last]  expressionorfor i in [first..last] then expressionorexpression for i in [first..last]for item in set  expressionorfor item in set then expressionorexpression for item in set
COBOLPERFORM procedure-1 «THROUGH procedure-2» ««WITH» TEST BEFORE» UNTIL condition[c]orPERFORM ««WITH» TEST BEFORE» UNTIL condition  expressionEND-PERFORMPERFORM procedure-1 «THROUGH procedure-2» «WITH» TEST AFTER UNTIL condition[c]orPERFORM «WITH» TEST AFTER UNTIL condition  expressionEND-PERFORMPERFORM procedure-1 «THROUGH procedure-2» VARYING i FROM first BY increment UNTIL i > last[d]orPERFORM VARYING i FROM first BY increment UNTIL i > last  expressionEND-PERFORM[d]
Rustwhile condition {   expression}loop {   expression     if condition {       break;  }}for i in first..last+1 {   expression}orfor i in first..=last {   expression}for item in set {   expression}[e]orset.into_iter().for_each(|item| expression);[e]
  • ^a "step n" is used to change the loop interval. If "step" is omitted, then the loop interval is 1.
  • ^b This implements the universal quantifier ("for all" or " ∀ {\displaystyle \forall } ") as well as the existential quantifier ("there exists" or " ∃ {\displaystyle \exists } ").
  • ^c THRU may be used instead of THROUGH.
  • ^d «IS» GREATER «THAN» may be used instead of >.
  • ^e Type of set expression must implement trait std::iter::IntoIterator.

Exceptions

Further information: Exception handling syntax

throwhandlerassertion
Ada22raise exception_name «with string_expression»begin  statementsexception  when exception_list1 => statements;  when exception_list2 => statements;...  «when others => statements;»end[b]pragma Assert («Check =>» boolean_expression ««Message =>» string_expression»)[function | procedure | entry] with  Pre => boolean_expression  Post => boolean_expressionany_type with Type_Invariant => boolean_expression
APL«string_expression» ⎕SIGNAL number_expression:Trap number«s»_expression  statements«:Case number«s»_expression  statements»...«:Else number«s»_expression  statements»: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 { instructionsSystem.Diagnostics.Debug.Assert(condition);orSystem.Diagnostics.Trace.Assert(condition);
Javatry { instructions } catch (exception) { instructions } ... «finally { instructionsassert condition «: description»;
JavaScripttry { instructions } catch (exception) { instructions} «finally { instructions?
Dtry { instructions } catch (exception) { instructions } ... «finally { instructionsassert(condition);
PHPtry { instructions } catch (exception) { instructions } ... «finally { instructionsassert(condition);
S-Langtry { instructions } catch «exception» { instructions } ... «finally { instructions?
Windows PowerShelltrap «[exception]» { instructions } ... instructionsortry { instructions } catch «[exception]» { instructions } ... «finally { instructions[Debug]::Assert(condition)
Objective-C@throw exception;@try { instructions } @catch (exception) { instructions } ... «@finally { instructionsNSAssert(condition, description);
Swiftthrow exception (2.x)do { try expression ... instructions } catch exception { instructions } ... (2.x)assert(condition«, description»)
Perldie exception;eval { instructions }; if ($@) { instructions }?
Rakutry { instructions CATCH { when exception { instructions } ...}}?
Rubyraise exceptionbegin  instructionsrescue exception  instructions...«else  instructions»«ensure  instructions»end
Smalltalkexception raiseinstructionBlock on: exception do: handlerBlockassert: conditionBlock
Common Lisp(error "exception")or(error  type  arguments)or(error (make-condition  type  arguments))(handler-case  (progn instructions)  (exception instructions)  ...)or(handler-bind  (condition     (lambda     instructions     «invoke-restart restart args»))...)[a](assert condition)or(assert condition  «(place)  «error»»)or(check-type var type)
Scheme (R6RS)(raise exception)(guard (con (condition instructions) ...) instructions)?
ISLISP(error "error-string" objects)or(signal-condition condition continuable)(with-handler  handler form*)?
Pascalraise Exception.Create()try Except on E: exception do begin instructions end; end;?
Visual BasicErr.Raise ERRORNUMBERWith New Try: On Error Resume Next  OneInstruction.Catch: On Error GoTo 0: Select Case .Number  Case SOME_ERRORNUMBER     instructionsEnd Select: End With'*** Try class ***Private mstrDescription As StringPrivate mlngNumber As LongPublic Sub Catch() mstrDescription = Err.Description mlngNumber = Err.NumberEnd SubPublic Property Get Number() As Long Number = mlngNumberEnd PropertyPublic Property Get Description() As String Description = mstrDescriptionEnd Property23Debug.Assert condition
Visual Basic .NETThrow exceptionorError errorcodeTry  instructionsCatch« name As exception»« When condition»  instructions...«Finally  instructions»End TrySystem.Diagnostics.Debug.Assert(condition)orSystem.Diagnostics.Trace.Assert(condition)
XojoRaise exceptionTry  instructionsCatch «exception»  instructions...«Finally  instructions»End Try
Pythonraise exceptiontry:Tab ↹instructionsexcept «exception»:Tab ↹instructions...«else:Tab ↹instructions»«finally:Tab ↹instructions»assert condition
Fortran
Forthcode THROWxt CATCH ( code or 0 )
OCamlraise exceptiontry expression with pattern -> expression ...assert condition
F#try expression with pattern -> expression ...ortry expression finally expression
Standard MLraise exception «arg»expression handle pattern => expression ...
Haskell (GHC)throw exceptionorthrowError expressioncatch tryExpression catchExpressionorcatchError tryExpression catchExpressionassert condition expression
COBOLRAISE «EXCEPTION» exceptionUSE «AFTER» EXCEPTION OBJECT class-name.orUSE «AFTER» EO class-name.orUSE «AFTER» EXCEPTION CONDITION exception-name «FILE file-name».orUSE «AFTER» EC exception-name «FILE file-name».
RustNo24assert!(condition)
  • ^a 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.
  • ^b 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)continuelabelbranch (goto)return value from generator
Ada25exit «loop_name» «when condition»label:goto label
ALGOL 68value exit; ...do statements; skip exit; label: statements odlabel: ...go to label; ...goto label; ...label; ...yield(value)

(Callback)26

APL:Leave:Continuelabel:labelor:GoTo label
C (C99)break;continue;label:goto label;
Objective-C
C++ (STL)
D
C#yield return value;
Javabreak «label»;continue «label»;
JavaScriptyield value«;»
PHPbreak «levels»;continue «levels»;goto label;yield «key =>» value;
Perllast «label»;next «label»;
Raku
Gobreak «label»continue «label»goto label
Swiftbreak «label»continue «label»
Bash shellbreak «levels»continue «levels»
Common Lisp(return)or(return-from block)or(loop-finish)(tagbody tag  ...  tag...)(go tag)
Scheme
ISLISP(return-from block)(tagbody tag  ...  tag...)(go tag)
Pascal (ISO)label:[a]goto label;
Pascal (FPC)break;continue;
Visual BasicExit blockAlternatively, for methods,Returnlabel:GoTo label
XojoContinue block
Visual Basic .NETYield value
Pythonbreakcontinueyield value
RPG IVLEAVE;ITER;
S-Langbreak;continue;
FortranEXITCYCLElabel[b]GOTO label
Rubybreaknext
Windows PowerShellbreak «label»continue
OCaml
F#
Standard ML
Haskell (GHC)
COBOLEXIT PERFORM or EXIT PARAGRAPH or EXIT SECTION or EXIT.EXIT PERFORM CYCLElabel «SECTION».GO TO label
  • ^a Pascal has declaration blocks. See functions.
  • ^b label must be a number between 1 and 99999.

Functions

See reflective programming for calling and declaring functions by strings.

calling a functionbasic/void functionvalue-returning functionrequired main function
Ada27foo «(parameters)»procedure foo «(parameters)» is begin statements end foofunction foo «(parameters)» return type is begin statements end foo
ALGOL 68foo «(parameters)»;proc foo = «(parameters)» void: ( instructions );proc foo = «(parameters)» rettype: ( instructions ...; retvalue );
APL«parameters» foo parametersfoo←{ statements }foo←{ statements }
C (C99)foo(«parameters»)void foo(«parameters») { instructions }type foo(«parameters») { instructions ... return value; }«global declarations»int main(«int argc, char *argv[]») {   instructions}
Objective-C
C++ (STL)
Javapublic static void main(String[] args) { instructions }orpublic static void main(String... args) { instructions }
Dint main(«char[][] args») { instructions}orint main(«string[] args») { instructions}orvoid main(«char[][] args») { instructions}orvoid 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_bodyMay instead return int.(starting with C# 7.1:) May return Task or Task<int>, and if so, may be async.
JavaScriptfunction foo(«parameters») { instructions }orvar foo = function («parameters») { instructions }orvar foo = new Function ("«parameter»", ..., "«last parameter»" "instructions");function foo(«parameters») { instructions ... return value; }
Gofunc foo(«parameters») { instructions }func foo(«parameters») type { instructions ... return value }func main() { instructions }
Swiftfunc foo(«parameters») { instructions }func foo(«parameters») -> type { instructions ... return value }
Common Lisp(foo «parameters»)(defun foo («parameters»)  instructions)or(setf (symbol-function 'symbol)  function)(defun foo («parameters»)  ...  value)
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»)  instructions)(defun foo («parameters»)  ...  value)
Pascalfoo«(parametersprocedure foo«(parameters)»; «forward;»[a]«label  label declarations»«const  constant declarations»«type  type declarations»«var  variable declarations»«local function declarations»begin  instructionsend;function foo«(parameters)»: type; «forward;»[a]«label  label declarations»«const  constant declarations»«type  type declarations»«var  variable declarations»«local function declarations»begin  instructions;  foo := valueend;program name;«label  label declarations»«const  constant declarations»«type  type declarations»«var  variable declarations»«function declarations»begin  instructionsend.
Visual BasicFoo(«parameters»)Sub Foo«(parameters)»  instructionsEnd SubFunction Foo«(parameters)»« As type»  instructions  Foo = valueEnd FunctionSub Main()  instructionsEnd Sub
Visual Basic .NETSame as above; alternatively:

Function Foo«(parameters)»« As type»  instructions  Return valueEnd FunctionThe 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»)  instructionsEnd SuborFunction Main(««ByVal »args() As String») As Integer  instructionsEnd Function
Xojo
Pythonfoo(«parameters»)def foo(«parameters»):Tab ↹instructionsdef foo(«parameters»):Tab ↹instructionsTab ↹return value
S-Langfoo(«parameters» «;qualifiers»)define foo («parameters») { instructions }define foo («parameters») { instructions ... return value; }public define slsh_main () { instructions }
Fortranfoo («arguments»)CALL sub_foo («arguments»)[c]SUBROUTINE sub_foo («arguments»)  instructionsEND SUBROUTINE[c]type FUNCTION foo («arguments»)  instructions  ...  foo = valueEND FUNCTION[c]PROGRAM main  instructionsEND PROGRAM
Forth«parameters» FOO: FOO « stack effect comment: ( before -- ) »  instructions;: FOO « stack effect comment: ( before -- after ) »  instructions;
PHPfoo(«parameters»)function foo(«parameters») { instructions }function foo(«parameters») { instructions ... return value; }
Perlfoo(«parameters»)or&foo«(parameterssub foo { «my (parameters) = @_;» instructions }sub foo { «my (parameters) = @_;» instructions... «return» value; }
Rakufoo(«parameters»)or&foo«(parameters«multi »sub foo(parameters) { instructions }«our «type» »«multi »sub foo(parameters) { instructions ... «return» value; }
Rubyfoo«(parametersdef foo«(parameters)»  instructionsenddef foo«(parameters)»  instructions  «return» valueend
Rustfoo(«parameters»)fn foo(«parameters») { instructions }fn foo(«parameters») -> type { instructions }fn main() { instructions }
Scalafoo«(parametersdef foo«(parameters)»«: Unit =» { instructions }def foo«(parameters)»«: type» = { instructions ... «return» value }def main(args: Array[String]) { instructions }
Windows PowerShellfoo «parameters»function foo { instructions };orfunction foo { «param(parametersinstructions }function foo «(parameters)» { instructions ... return value };orfunction foo { «param(parametersinstructions ... return value }
Bash shellfoo «parameters»function foo {  instructions}orfoo () {  instructions}function foo {  instructions  return «exit_code»}orfoo () {   instructions  return «exit_code»}
  • parameters
    • $n ($1, $2, $3, ...)
    • $@ (all parameters)
    • $# (the number of parameters)
    • $0 (this function name)
OCamlfoo parameterslet «rec» foo parameters = instructionslet «rec» foo parameters = instructions... return_value
F#[<EntryPoint>] let main args = instructions
Standard MLfun foo parameters = ( instructions )fun foo parameters = ( instructions... return_value )
Haskellfoo parameters = doTab ↹instructionsfoo parameters = return_valueorfoo parameters = doTab ↹instructionsTab ↹return value«main :: IO ()»main = do instructions
Eiffelfoo («parameters»)foo («parameters»)  require     preconditions  do     instructions  ensure     postconditions  endfoo («parameters»): type  require     preconditions  do     instructions     Result := value  ensure     postconditions  end[b]
CoffeeScriptfoo()foo = ->foo = -> value
foo parametersfoo = () ->foo = ( parameters ) -> value
COBOLCALL "foo" «USING parameters»  «exception-handling»«END-CALL»[d]«IDENTIFICATION DIVISION.»PROGRAM-ID. foo.«other divisions...»PROCEDURE DIVISION «USING parameters».  instructions.«IDENTIFICATION DIVISION.»PROGRAM-ID/FUNCTION-ID. fooother divisions...»DATA DIVISION.«other sections...»LINKAGE SECTION.«parameter definitions...»variable-to-return definition«other sections...»PROCEDURE DIVISION «USING parameters» RETURNING variable-to-return.  instructions.
«FUNCTION» foo«(«parameters»)»
  • ^a Pascal requires "forward;" for forward declarations.
  • ^b Eiffel allows the specification of an application's root class and feature.
  • ^c In Fortran, function/subroutine parameters are called arguments (since PARAMETER is a language keyword); the CALL keyword is required for subroutines.
  • ^d Instead of using "foo", a string variable may be used instead containing the same value.

Type conversions

Where string is a signed decimal number:

string to integerstring to long integerstring to floating pointinteger to stringfloating point to string
Ada28Integer'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 formatsWith 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));orgetf(proxy, ($dddd$, ivar));getf(proxy, ($g$, livar));orgetf(proxy, ($8d$, livar));getf(proxy, ($g$, rvar));orgetf(proxy, ($8d.4dE2d$, rvar));putf(proxy, ($g$, ival));orputf(proxy, ($4d$, ival));putf(proxy, ($g(width, places, exp)$, rval));orputf(proxy, ($8d.4dE2d$, rval));
APLstring_expressionstring_expressionstring_expressioninteger_expressionfloat_expression
C (C99)integer = atoi(string);long = atol(string);float = atof(string);sprintf(string, "%i", integer);sprintf(string, "%f", float);
Objective-Cinteger = [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++11integer = «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();
Dinteger = 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)
Javainteger = 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);
JavaScript[a]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}`
Gointeger, 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)
Rust[d]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>))
Pascalinteger := StrToInt(string);float := StrToFloat(string);string := IntToStr(integer);string := FloatToStr(float);
Visual Basicinteger = 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()
Xojointeger = Val(string)long = Val(string)double = Val(string)double = CDbl(string)string = CStr(number)orstring = Str(number)
Pythoninteger = int(string)long = long(string)float = float(string)string = str(number)
S-Langinteger = atoi(string);long = atol(string);float = atof(string);string = string(number);
FortranREAD(string,format) numberWRITE(string,format) number
PHPinteger = intval(string);orinteger = (int)string;float = floatval(string);float = (float)string;string = "$number";orstring = strval(number);orstring = (string)number;
Perl[b]number = 0 + string;string = "number";
Rakunumber = +string;string = ~number;
Rubyinteger = string.to_iorinteger = Integer(string)float = string.to_ffloat = Float(string)string = number.to_s
Scalainteger = string.toIntlong = string.toLongfloat = string.toFloatdouble = string.toDoublestring = number.toString
Smalltalkinteger := Integer readFrom: stringfloat := Float readFrom: stringstring := number asString
Windows PowerShellinteger = [int]stringlong = [long]stringfloat = [float]stringstring = [string]number;orstring = "number";orstring = (number).ToString()
OCamllet integer = int_of_string stringlet float = float_of_string stringlet string = string_of_int integerlet string = string_of_float float
F#let integer = int stringlet integer = int64 stringlet float = float stringlet string = string number
Standard MLval integer = Int.fromString stringval float = Real.fromString stringval string = Int.toString integerval string = Real.toString float
Haskell (GHC)number = read stringstring = show number
COBOLMOVE «FUNCTION» NUMVAL(string)[c] TO numberMOVE number TO numeric-edited
  • ^a JavaScript only uses floating point numbers so there are some technicalities.29
  • ^b Perl doesn't have separate types. Strings and numbers are interchangeable.
  • ^c NUMVAL-C or NUMVAL-F may be used instead of NUMVAL.
  • ^ str::parse is available to convert any type that has an implementation of the std::str::FromStr trait. Both str::parse and FromStr::from_str return a Result that contains the specified type if there is no error. The turbofish (::<_>) on str::parse can be omitted if the type can be inferred from context.

Standard stream I/O

read fromwrite to
stdinstdoutstderr
Ada30Get (x)Put (x)Put (Standard_Error, x)
ALGOL 68readf(($format$, x));orgetf(stand in, ($format$, x));printf(($format$, x));orputf(stand out, ($format$, x));putf(stand error, ($format$, x));[a]
APLx←⎕←x⍞←x
C (C99)scanf(format, &x);orfscanf(stdin, format, &x);[b]printf(format, x);orfprintf(stdout, format, x);[c]fprintf(stderr, format, x);[d]
Objective-Cdata = [[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();orx = Console.ReadLine();Console.Write(«format, »x);orConsole.WriteLine(«format, »x);Console.Error.Write(«format, »x);orConsole.Error.WriteLine(«format, »x);
Dx = std.stdio.readln()std.stdio.write(x)orstd.stdio.writeln(x)orstd.stdio.writef(format, x)orstd.stdio.writefln(format, x)stderr.write(x)orstderr.writeln(x)orstd.stdio.writef(stderr, format, x)orstd.stdio.writefln(stderr, format, x)
Javax = System.in.read();orx = new Scanner(System.in).nextInt();orx = new Scanner(System.in).nextLine();System.out.print(x);orSystem.out.printf(format, x);orSystem.out.println(x);System.err.print(x);orSystem.err.printf(format, x);orSystem.err.println(x);
Gofmt.Scan(&x)orfmt.Scanf(format, &x)orx = bufio.NewReader(os.Stdin).ReadString('\n')fmt.Println(x)orfmt.Printf(format, x)fmt.Fprintln(os.Stderr, x)orfmt.Fprintf(os.Stderr, format, x)
Swiftx = readLine() (2.x)print(x) (2.x)println(x) (1.x)
JavaScriptWeb Browser implementationdocument.write(x)
JavaScriptActive Server PagesResponse.Write(x)
JavaScriptWindows Script Hostx = WScript.StdIn.Read(chars)orx = WScript.StdIn.ReadLine()WScript.Echo(x)orWScript.StdOut.Write(x)orWScript.StdOut.WriteLine(x)WScript.StdErr.Write(x)orWScript.StdErr.WriteLine(x)
Common Lisp(setf x (read-line))(princ x)or(format t format x)(princ x *error-output*)or(format *error-output* format x)
Scheme (R6RS)(define x (read-line))(display x)or(format #t format x)(display x (current-error-port))or(format (current-error-port) format x)
ISLISP(setf x (read-line))(format (standard-output) format x)(format (error-output) format x)
Pascalread(x);orreadln(x);write(x);orwriteln(x);write(stderr, x);orwriteln(stderr, x);
Visual BasicInput« promptxPrint xor? x
Visual Basic .NETx = Console.Read()orx = Console.ReadLine()Console.Write(«formatx)orConsole.WriteLine(«format, »x)Console.Error.Write(«format, »x)orConsole.Error.WriteLine(«format, »x)
Xojox = StandardInputStream.Read()orx = StandardInputStreame.ReadLine()StandardOutputStream.Write(x)orStandardOutputStream.WriteLine(x)StdErr.Write(x)orStdErr.WriteLine(x)
Python 2.xx = raw_input(«prompt»)print xorsys.stdout.write(x)print >> sys.stderr, xorsys.stderr.write(x)
Python 3.xx = input(«prompt»)print(, end=""»)print(, end=""», file=sys.stderr)
S-Langfgets (&x, stdin)fputs (x, stdout)fputs (x, stderr)
FortranREAD(*,format) variable names orREAD(INPUT_UNIT,format) variable names[e]WRITE(*,format) expressions orWRITE(OUTPUT_UNIT,format) expressions[e]WRITE(ERROR_UNIT,format) expressions[e]
Forthbuffer length ACCEPT ( # chars read )KEY ( char )buffer length TYPEchar EMIT
PHP$x = fgets(STDIN);or$x = fscanf(STDIN, format);print x;orecho x;orprintf(format, x);fprintf(STDERR, format, x);
Perl$x = <>;or$x = <STDIN>;print x;orprintf format, x;print STDERR x;orprintf STDERR format, x;
Raku$x = $*IN.get;x.printorx.sayx.noteor$*ERR.print(x)or$*ERR.say(x)
Rubyx = getsputs xorprintf(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;orWrite-Output x;orecho xWrite-Error x
OCamllet x = read_int ()orlet str = read_line ()orScanf.scanf format (fun x ... -> ...)print_int xorprint_endline strorPrintf.printf format x ...prerr_int xorprerr_endline strorPrintf.eprintf format x ...
F#let x = System.Console.ReadLine()printf format x ...orprintfn format x ...eprintf format x ...oreprintfn format x ...
Standard MLval str = TextIO.inputLIne TextIO.stdInprint strTextIO.output (TextIO.stdErr, str)
Haskell (GHC)x <- readLnorstr <- getLineprint xorputStrLn strhPrint stderr xorhPutStrLn stderr str
COBOLACCEPT xDISPLAY x
  • ^a ALGOL 68 additionally as the "unformatted" transput routines: read, write, get, and put.
  • ^b gets(x) and fgets(x, length, stdin) read unformatted text from stdin. Use of gets is not recommended.
  • ^c puts(x) and fputs(x, stdout) write unformatted text to stdout.
  • ^d fputs(x, stderr) writes unformatted text to stderr
  • ^e INPUT_UNIT, OUTPUT_UNIT, ERROR_UNIT are defined in the ISO_FORTRAN_ENV module.31

Reading command-line arguments

Argument valuesArgument countsProgram name / Script name
Ada32Argument (n)Argument_CountCommand_Name
C (C99)argv[n]argcfirst argument
Objective-C
C++
C#args[n]args.LengthAssembly.GetEntryAssembly().Location;
Javaargs.length
Dfirst argument
JavaScriptWindows Script Host implementationWScript.Arguments(n)WScript.Arguments.lengthWScript.ScriptNameorWScript.ScriptFullName
Goos.Args[n]len(os.Args)first argument
Rust[a]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()
SwiftProcess.arguments[n] orProcess.unsafeArgv[n]Process.arguments.count orProcess.argcfirst argument
Common Lisp???
Scheme (R6RS)(list-ref (command-line) n)(length (command-line))first argument
ISLISP
PascalParamStr(n)ParamCountfirst argument
Visual BasicCommand[b]App.Path
Visual Basic .NETCmdArgs(n)CmdArgs.Length[Assembly].GetEntryAssembly().Location
XojoSystem.CommandLine(string parsing)Application.ExecutableFile.Name
Pythonsys.argv[n]len(sys.argv)first argument
S-Lang__argv[n]__argcfirst argument
FortranDO i = 1,argc  CALL GET_COMMAND_ARGUMENT (i,argv(i))ENDDOargc = COMMAND_ARGUMENT_COUNT ()CALL GET_COMMAND_ARGUMENT (0,progname)
PHP$argv[n]$argcfirst argument
Bash shell$n ($1, $2, $3, ...)$@ (all arguments)$#$0
Perl$ARGV[n]scalar(@ARGV)$0
Raku@*ARGS[n]@*ARGS.elems$PROGRAM_NAME
RubyARGV[n]ARGV.size$0
Windows PowerShell$args[n]$args.Length$MyInvocation.MyCommand.Name
OCamlSys.argv.(n)Array.length Sys.argvfirst argument
F#args.[n]args.LengthAssembly.GetEntryAssembly().Location
Standard MLList.nth (CommandLine.arguments (), n)length (CommandLine.arguments ())CommandLine.name ()
Haskell (GHC)do { args <- System.getArgs; return length args !! n}do { args <- System.getArgs; return length args}System.getProgName
COBOL[c]
  • ^a 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.
  • ^b In Visual Basic, command-line arguments are not separated. Separating them requires a split function Split(string).
  • ^c 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 commandExecute programReplace current program with new executed program
Ada33Not part of the language standard. Commonly done by compiler provided packages or by interfacing to C or POSIX.34
Csystem("command");execl(path, args);orexecv(path, arglist);
C++
Objective-C[NSTask launchedTaskWithLaunchPath:(NSString *)path arguments:(NSArray *)arguments];
C#System.Diagnostics.Process.Start(path, argstring);
F#
Goexec.Run(path, argv, envv, dir, exec.DevNull, exec.DevNull, exec.DevNull)os.Exec(path, argv, envv)
Visual BasicInteraction.Shell(command «, WindowStyle» «, isWaitOnReturn»)
Visual Basic .NETMicrosoft.VisualBasic.Interaction.Shell(command «, WindowStyle» «, isWaitOnReturn»)System.Diagnostics.Process.Start(path, argstring)
XojoShell.Execute(command «, Parameters»)FolderItem.Launch(parameters, activate)
Dstd.process.system("command");std.process.execv(path, arglist);
JavaRuntime.exec(command);ornew ProcessBuilder(command).start();
JavaScriptWindows Script Host implementationWScript.CreateObject ("WScript.Shell").Run(command «, WindowStyle» «, isWaitOnReturn»);WshShell.Exec(command)
Common Lisp(uiop:run-program command)
Scheme(system command)
ISLISP
Pascalsystem(command);
OCamlSys.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 argsorUnix.execve prog args env
Standard MLOS.Process.system commandUnix.execute (path, args)Posix.Process.exec (path, args)
Haskell (GHC)System.system commandSystem.Process.runProcess path args ...Posix.Process.executeFile path True args ...
Perlsystem(command)or$output = `command`or$output = qx(command)exec(path, args)
Rubysystem(command)oroutput = `command`exec(path, args)
PHPsystem(command)or$output = `command`orexec(command)orpassthru(command)
Pythonos.system(command)orsubprocess.Popen(command)subprocess.call(["program", "arg1", "arg2", ...])os.execv(path, args)
S-Langsystem(command)
FortranCALL EXECUTE_COMMAND_LINE (COMMAND «, WAIT» «, EXITSTAT» «, CMDSTAT» «, CMDMSG»)[a]
Windows PowerShell[Diagnostics.Process]::Start(command)«Invoke-Item »program arg1 arg2 ...
Bash shelloutput=`command`oroutput=$(command)program arg1 arg2 ...

^a Fortran 2008 or newer.35

See also

References

  1. Ada Reference Manual – Language and Standard Libraries; ISO/IEC 8652:201x (E), "Reference Manual" (PDF). Archived from the original (PDF) on 2011-04-27. Retrieved 2013-07-19. https://web.archive.org/web/20110427190723/http://www.ada-auth.org/standards/12rm/RM-Final.pdf

  2. "Common Lisp HyperSpec (TM)". lispworks.com. Retrieved 30 January 2017. http://www.lispworks.com/documentation/HyperSpec/Front/index.htm

  3. "www.islisp.info: Specification". islisp.info. Archived from the original on 22 January 2016. Retrieved 30 January 2017. https://web.archive.org/web/20160122121427/http://islisp.info/specification.html

  4. "selected_int_kind in Fortran Wiki". fortranwiki.org. Retrieved 30 January 2017. http://fortranwiki.org/fortran/show/selected_int_kind

  5. "Erlang — Types and Function Specifications". erlang.org. Retrieved 30 January 2017. http://www.erlang.org/doc/reference_manual/typespec.html

  6. "Erlang — Advanced". erlang.org. Retrieved 30 January 2017. http://www.erlang.org/doc/efficiency_guide/advanced.html

  7. Ada Reference Manual – Language and Standard Libraries; ISO/IEC 8652:201x (E), "Reference Manual" (PDF). Archived from the original (PDF) on 2011-04-27. Retrieved 2013-07-19. https://web.archive.org/web/20110427190723/http://www.ada-auth.org/standards/12rm/RM-Final.pdf

  8. 8.5 The Number Type https://www.mozilla.org/js/language/E262-3.pdf

  9. "selected_real_kind in Fortran Wiki". fortranwiki.org. Retrieved 30 January 2017. http://fortranwiki.org/fortran/show/selected_real_kind

  10. Ada Reference Manual – Language and Standard Libraries; ISO/IEC 8652:201x (E), "Reference Manual" (PDF). Archived from the original (PDF) on 2011-04-27. Retrieved 2013-07-19. https://web.archive.org/web/20110427190723/http://www.ada-auth.org/standards/12rm/RM-Final.pdf

  11. "The GNU C Library: Complex Numbers". gnu.org. Retrieved 30 January 2017. https://www.gnu.org/software/libc/manual/html_node/Complex-Numbers.html#Complex-Numbers

  12. "selected_real_kind in Fortran Wiki". fortranwiki.org. Retrieved 30 January 2017. http://fortranwiki.org/fortran/show/selected_real_kind

  13. Ada Reference Manual – Language and Standard Libraries; ISO/IEC 8652:201x (E), "Reference Manual" (PDF). Archived from the original (PDF) on 2011-04-27. Retrieved 2013-07-19. https://web.archive.org/web/20110427190723/http://www.ada-auth.org/standards/12rm/RM-Final.pdf

  14. "selected_int_kind in Fortran Wiki". fortranwiki.org. Retrieved 30 January 2017. http://fortranwiki.org/fortran/show/selected_int_kind

  15. Ada Reference Manual – Language and Standard Libraries; ISO/IEC 8652:201x (E), "Reference Manual" (PDF). Archived from the original (PDF) on 2011-04-27. Retrieved 2013-07-19. https://web.archive.org/web/20110427190723/http://www.ada-auth.org/standards/12rm/RM-Final.pdf

  16. Ada Reference Manual – Language and Standard Libraries; ISO/IEC 8652:201x (E), "Reference Manual" (PDF). Archived from the original (PDF) on 2011-04-27. Retrieved 2013-07-19. https://web.archive.org/web/20110427190723/http://www.ada-auth.org/standards/12rm/RM-Final.pdf

  17. Ada Reference Manual – Language and Standard Libraries; ISO/IEC 8652:201x (E), "Reference Manual" (PDF). Archived from the original (PDF) on 2011-04-27. Retrieved 2013-07-19. https://web.archive.org/web/20110427190723/http://www.ada-auth.org/standards/12rm/RM-Final.pdf

  18. "Grammar vb". Visual Basic Language Specification. 2016-06-17. Archived from the original on 2019-08-29. Retrieved 2019-08-29. https://ljw1004.github.io/vbspec/vb.html

  19. Ada Reference Manual – Language and Standard Libraries; ISO/IEC 8652:201x (E), "Reference Manual" (PDF). Archived from the original (PDF) on 2011-04-27. Retrieved 2013-07-19. https://web.archive.org/web/20110427190723/http://www.ada-auth.org/standards/12rm/RM-Final.pdf

  20. Ada Reference Manual – Language and Standard Libraries; ISO/IEC 8652:201x (E), "Reference Manual" (PDF). Archived from the original (PDF) on 2011-04-27. Retrieved 2013-07-19. https://web.archive.org/web/20110427190723/http://www.ada-auth.org/standards/12rm/RM-Final.pdf

  21. "for...of". mozilla.org. Retrieved 30 January 2017. https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...of

  22. Ada Reference Manual – Language and Standard Libraries; ISO/IEC 8652:201x (E), "Reference Manual" (PDF). Archived from the original (PDF) on 2011-04-27. Retrieved 2013-07-19. https://web.archive.org/web/20110427190723/http://www.ada-auth.org/standards/12rm/RM-Final.pdf

  23. "Try-Catch for VB". google.com. Archived from the original on 16 April 2016. Retrieved 30 January 2017. https://web.archive.org/web/20160416093023/https://sites.google.com/site/truetryforvisualbasic/

  24. Klabnik, Steve; Nichols, Carol. "Error Handling". The Rust Programming Language. https://doc.rust-lang.org/book/ch09-00-error-handling.html

  25. Ada Reference Manual – Language and Standard Libraries; ISO/IEC 8652:201x (E), "Reference Manual" (PDF). Archived from the original (PDF) on 2011-04-27. Retrieved 2013-07-19. https://web.archive.org/web/20110427190723/http://www.ada-auth.org/standards/12rm/RM-Final.pdf

  26. "Prime decomposition – Rosetta Code". rosettacode.org. Retrieved 30 January 2017. http://rosettacode.org/wiki/Prime_decomposition#ALGOL_68

  27. Ada Reference Manual – Language and Standard Libraries; ISO/IEC 8652:201x (E), "Reference Manual" (PDF). Archived from the original (PDF) on 2011-04-27. Retrieved 2013-07-19. https://web.archive.org/web/20110427190723/http://www.ada-auth.org/standards/12rm/RM-Final.pdf

  28. Ada Reference Manual – Language and Standard Libraries; ISO/IEC 8652:201x (E), "Reference Manual" (PDF). Archived from the original (PDF) on 2011-04-27. Retrieved 2013-07-19. https://web.archive.org/web/20110427190723/http://www.ada-auth.org/standards/12rm/RM-Final.pdf

  29. 8.5 The Number Type https://www.mozilla.org/js/language/E262-3.pdf

  30. Ada Reference Manual – Language and Standard Libraries; ISO/IEC 8652:201x (E), "Reference Manual" (PDF). Archived from the original (PDF) on 2011-04-27. Retrieved 2013-07-19. https://web.archive.org/web/20110427190723/http://www.ada-auth.org/standards/12rm/RM-Final.pdf

  31. "iso_fortran_env in Fortran Wiki". fortranwiki.org. Retrieved 30 January 2017. http://fortranwiki.org/fortran/show/iso_fortran_env

  32. Ada Reference Manual – Language and Standard Libraries; ISO/IEC 8652:201x (E), "Reference Manual" (PDF). Archived from the original (PDF) on 2011-04-27. Retrieved 2013-07-19. https://web.archive.org/web/20110427190723/http://www.ada-auth.org/standards/12rm/RM-Final.pdf

  33. Ada Reference Manual – Language and Standard Libraries; ISO/IEC 8652:201x (E), "Reference Manual" (PDF). Archived from the original (PDF) on 2011-04-27. Retrieved 2013-07-19. https://web.archive.org/web/20110427190723/http://www.ada-auth.org/standards/12rm/RM-Final.pdf

  34. "Execute a system command – Rosetta Code". rosettacode.org. Retrieved 30 January 2017. http://rosettacode.org/wiki/Execute_a_system_command#Ada

  35. "EXECUTE_COMMAND_LINE – The GNU Fortran Compiler". gnu.org. Retrieved 30 January 2017. https://gcc.gnu.org/onlinedocs/gfortran/EXECUTE_005fCOMMAND_005fLINE.html