fbpx
Wikipedia

Comparison of programming languages (basic instructions)

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 edit

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 edit

Integers edit

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 - 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_t uint8_t int16_t uint16_t int32_t uint32_t int64_t uint64_t intptr_t[c] size_t[c]
C++ (C++11 fixed-width)
C (C99 variable-width) signed char unsigned char short[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_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 char[b] 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
Swift Int8 UInt8 Int16 UInt16 Int32 UInt32 Int64 UInt64 Int UInt
D byte ubyte short ushort int uint long ulong 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
Visual Basic Byte Integer Long
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
Python 2.x int long
Python 3.x int
S-Lang
Fortran INTEGER(KIND = n)[f] INTEGER(KIND = n)[f] INTEGER(KIND = n)[f] INTEGER(KIND = n)[f]
PHP int[m] int[m] [e]
Perl 5 [d] [d] [d] [d] [d] Math::BigInt
Raku int8 uint8 int16 uint16 int32 uint32 int64 uint64 Int
Ruby Fixnum Bignum
Erlang[n] integer() integer()[o]
Scala Byte Short Char[l] Int Long scala.math.BigInt
Seed7 integer bigInteger
Smalltalk SmallInteger[i] LargeInteger[i]
Windows PowerShell
OCaml int32 int64 int or nativeint open Big_int;; or big_int
F# sbyte byte int16 uint16 int32 or int uint32 uint64 nativeint unativeint bigint
Standard ML Word8.word 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
COBOL[h] BINARY-CHAR «SIGNED» BINARY-CHAR UNSIGNED BINARY-SHORT «SIGNED» BINARY-SHORT UNSIGNED BINARY-LONG «SIGNED» BINARY-LONG UNSIGNED BINARY-DOUBLE «SIGNED» BINARY-DOUBLE UNSIGNED
Mathematica Integer
Wolfram Language Integer
  • ^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[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.
  • ^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_KIND[4] 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 edit

Single precision Double precision Other precision Processor dependent
Ada[1] Float Long_Float
ALGOL 68 real[a] long real[a] short real, long long real, etc.[d]
C float[b] double long double[f]
C++ (STL)
Objective-C (Cocoa) CGFloat
C# float
Java
Go float32 float64
Rust f32 f64
Swift Float or Float32 Double or Float64 Float80[g] 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
Visual Basic .NET
Xojo
Python float
JavaScript Number[7]
S-Lang
Fortran REAL(KIND = n)[c]
PHP float
Perl
Raku num32 num64 Num
Ruby Float
Scala Float Double
Seed7 float
Smalltalk Float Double
Windows PowerShell
OCaml float
F# float32
Standard ML real
Haskell (GHC) Float Double
Eiffel REAL_32 REAL_64
COBOL FLOAT-BINARY-7[e] FLOAT-BINARY-34[e] FLOAT-SHORT, FLOAT-LONG, FLOAT-EXTENDED
Mathematica Real
  • ^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_KIND[8] 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 edit

Integer Single precision Double precision Half and Quadruple precision etc.
Ada[1] Complex[b] Complex[b] Complex[b]
ALGOL 68 compl long compl etc. short compl etc. and long long compl etc.
C (C99)[9] float complex double complex
C++ (STL) std::complex<float> std::complex<double>
C# System.Numerics.Complex
(.NET 4.0)
Java
Go complex64 complex128
D cfloat cdouble
Objective-C
Common Lisp (complex integer) (complex single-float) (complex double-float) complex
Scheme
Pascal
Visual Basic
Visual Basic .NET System.Numerics.Complex
(.NET 4.0)
Perl Math::Complex
Raku complex64 complex128 Complex
Python complex
JavaScript
S-Lang
Fortran COMPLEX(KIND = n)[a]
Ruby Complex Complex
Scala
Seed7 complex
Smalltalk Complex Complex Complex
Windows PowerShell
OCaml Complex.t
F# System.Numerics.Complex
(.NET 4.0)
Standard ML
Haskell (GHC) Complex.Complex Float Complex.Complex Double
Eiffel
COBOL
Mathematica Complex Complex
  • ^a The value of n is provided by the SELECTED_REAL_KIND[8] intrinsic function.
  • ^b Generic type which can be instantiated with any base floating point type.

Other variable types edit

Text Boolean Enumeration Object/Universal
Character String[a]
Ada[1] Character String, Bounded_String, Unbounded_String Boolean (item1, item2, ...) tagged null record
ALGOL 68 char string, bytes bool, bits — - User defined
C (C99) char, wchar_t bool[b] 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 (
   item1 = iota
   item2
   ...
)
interface{}
Rust char String bool enum name { item1« = value», item2« = 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 boolean ( item1, item2, ... )
Object Pascal (Delphi) string variant
Visual Basic String Boolean Enum name
   item1 «= value»
   item2 «= value»
   ...

End Enum
[[Variant type|Variant]]
Visual Basic .NET Char Object
Xojo Object or Variant
Python [d] str bool from enum import Enum
class Name(Enum):
   item1 = value
   item2 = value
   ...
object
JavaScript [d] String Boolean Object
S-Lang
Fortran CHARACTER(LEN = *) CHARACTER(LEN = :), allocatable LOGICAL(KIND = n)[f] CLASS(*)
PHP [d] string bool (type declaration omitted)
Perl [d] UNIVERSAL
Raku Char Str Bool enum name<item1 item2 ...>
enum name <<:item1(value) :item2(value) ..>>
Mu
Ruby [d] String Object[c] Object
Scala Char String Boolean object name extends Enumeration {
   val item1, item2, ... = Value
}
Any
Seed7 char string boolean const type: name is new enum
   item1,
   item2,
   ...
end enum;
Windows PowerShell
OCaml char string bool [e]
F# type name = item1 = value |item2 = value | ... obj
Standard ML [e]
Haskell (GHC) Char String Bool [e]
Eiffel CHARACTER STRING BOOLEAN ANY
COBOL PIC X PIC 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_KIND[4] intrinsic function.

Derived types edit

Array edit

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][a] type name[size1][size2][a] 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[,,...] System.Collections.ArrayList
or
System.Collections.Generic.List<type>
Java type[][b] type[][]...[b] 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 Array[d]
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 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 type array of array ... of type
Visual Basic Dim x(last) As type Dim x(last1, last2,...) As type
Visual Basic .NET type() type(,,...) 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[,,...]
OCaml type array type array ... array
F# type []
or
type array
type [,,...] 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». 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 edit

Simple composite types Algebraic data types Unions
Records Tuple expression
Ada[1] type 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 68 struct (modename «fieldname», ...); Required types and operators can be user-defined union (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
D struct name {type name;...} std.variant.Algebraic!(type,...) union {type name;...}
Go struct {
  «name» type
  ...
}
Rust struct name {name: type, ...} (val1, val2, ... ) enum name { Foo(types), ...} union name {name: type, ...}
Swift struct 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
Pascal record
  name: type;
  ...
end
record
  case type of
  value: (types);
  ...
end
Visual Basic
Visual Basic .NET Structure name
  Dim name As type
  ...
End Structure
(val1, val2, ... )
Python [a] «(»val1, val2, val3, ... «)»
S-Lang struct {name [=value], ...}
Fortran TYPE name
  type
 :: name
  ...
END TYPE
PHP [a]
Perl [d]
Raku [a]
Ruby OpenStruct.new({:name => value})
Scala case class namevar» name: type, ...) (val1, val2, val3, ... ) abstract class name
  case class Fooparameters») extends name
  case class Barparameters») extends name
  ...

or
abstract class name
  case object Foo extends name
  case object Bar extends name
  ...

or a combination of case classes and case objects
Windows PowerShell
OCaml type name = {«mutable» name : type;...} «(»val1, val2, val3, ... «)» type name = Foo «of type» | Bar «of type» | ...
F#
Standard ML type name = {name : type,...} (val1, val2, val3, ... ) datatype name = Foo «of type» | Bar «of type» | ...
Haskell data Name = Constr {name :: type,...} data Name = Foo «types» | Bar «types» | ...
COBOL level-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 edit

variable constant type synonym
Ada[1] identifier : type« := initial_value»[e] 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;
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
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;
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)
Pascal[a] 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      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
Xojo Dim name «As type»« = initial_value»
Python name«: type» = initial_value synonym = type[b]
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+)
Perl «my» $name« = initial_value»;[c] use constant name => value;
Raku «my «type»» $name« = initial_value»;[c] «my «type»» constant name = value; ::synonym ::= type
Ruby name = initial_value Name = value synonym = type[b]
Scala var name«: type» = initial_value val name«: type» = value type synonym = type
Windows PowerShell «[type]» $name = initial_value
Bash shell name=initial_value
OCaml let name« : type ref» = ref value[d] let name «: type» = value type synonym = type
F# let mutable name «: type» = value
Standard ML val name «: type ref» = ref value[d] 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
  • ^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 edit

Conditional statements edit

if else if select case conditional expression
Ada[1] if condition then
  statements
«else
  statements»
end if
if condition1 then
  statements
elsif condition2 then
  statements
...
«else
  statements»
end if
case 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»
)
Seed7 if condition then
  statements
«else
  statements»
end if
if condition1 then
  statements
elsif condition2 then
  statements
...
«else
  statements»
end if
case expression of
  when set1 : statements
  ...
  «otherwise: statements»
end case
Modula-2 if condition then
  statements
«else
  statements»
end
if condition1 then
  statements
elsif condition2 then
  statements
...
«else
  statements»
end
case expression of
  caseLabelList : statements |
  ...
  «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 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) instructions
else if (condition) instructions
...
«else instructions»

or
if (condition) instructions
else { 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) instructions
else 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 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 {
  case condition: instructions
  ...
  «default: instructions»
}
switch variable {
  case case1: instructions
  ...
  «default: instructions»
}
Swift if condition {instructions}
«else {instructions
if condition {instructions}
else if condition {instructions}
...
«else {instructions
switch variable {
  case case1: instructions
  ...
  «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) {
  when (case1) { instructions }
  ...
  «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 {
  when case1 { instructions }
  ...
  «default { instructions
}
condition ?? valueIfTrue !! valueIfFalse
Ruby if condition
  instructions
«else
  instructions»
if condition
  instructions
elsif condition
  instructions
...
«else
  instructions»
end
case variable
  when case1
     instructions
  ...
  «else
     instructions»
end
condition ? valueIfTrue : valueIfFalse
Scala if (condition) {instructions}
«else {instructions
if (condition) {instructions}
else if (condition) {instructions}
...
«else {instructions
expression match {
  case pattern1 => expression
  case pattern2 => expression
  ...
  «case _ => expression»
}
[b]
if (condition) valueIfTrue else valueIfFalse
Smalltalk condition ifTrue:
  trueBlock
«ifFalse:
  falseBlock»
end
condition 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)
Pascal if condition then begin
  instructions
end
«else begin
  instructions
end»'
[c]
if condition then begin
  instructions
end
else if condition then begin
  instructions
end
...
«else begin
  instructions
end»
[c]
case variable of
  case1: instructions
  ...
  «else: instructions»
end
[c]
Visual Basic If condition Then
  instructions
«Else
  instructions»
End If

Single-line, when instructions are instruction1 : instruction2 : ...:
If condition Then instructions «Else instructions»
If condition Then
  instructions
ElseIf condition Then
  instructions
...
«Else
  instructions»
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» variable
  Case case_pattern1
     instructions
  ...
  «Case Else
     instructions»
End Select
IIf(condition, valueIfTrue, valueIfFalse)
Visual Basic .NET If(condition, valueIfTrue, valueIfFalse)
Xojo
Python[a] if condition :
Tab ↹instructions
«else:
Tab ↹instructions»
if condition :
Tab ↹instructions
elif condition :
Tab ↹instructions
...
«else:
Tab ↹instructions»
Python 3.10+:
match variable:
Tab ↹case case1:
Tab ↹Tab ↹instructions
Tab ↹case case2:
Tab ↹Tab ↹instructions
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) THEN
  instructions
ELSE
  instructions
ENDIF
IF (condition) THEN
  instructions
ELSEIF (condition) THEN
  instructions
...
ELSE
  instructions
ENDIF
SELECT CASE(variable)
  CASE (case1)
     instructions
  ...
  CASE DEFAULT
     instructions
END SELECT
Forth condition IF instructions « ELSE instructions» THEN condition IF instructions ELSE condition IF instructions THEN THEN value CASE
  case OF instructions ENDOF
  case OF instructions ENDOF
     default 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
  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 then
Tab ↹instructions
«else
Tab ↹instructions»

Verbose syntax mode:
Same as Standard ML.

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

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 of
  pattern1 => expression
  | pattern2 => expression
  ...
  «| _ => expression»
[b]
Haskell (GHC) if condition then expression else expression
or
when condition (do instructions)
or
unless notcondition (do instructions)
result | condition = expression
  | condition = expression
  | otherwise = expression
case value of {
  pattern1 -> expression;
  pattern2 -> expression;
  ...
  «_ -> expression»
}
[b]
Bash shell if condition-command; then
  expression
«else
  expression»
fi
if condition-command; then
  expression
elif condition-command; then
  expression
«else
  expression»
fi
case "$variable" in
  "$condition1" )
     command...
  "$condition2" )
     command...

esac
CoffeeScript if condition then expression «else expression»
or
if condition
  expression

«else
  expression»

or
expression if condition
or
unless condition
  expression
«else
  expression»

or
expression unless condition
if condition then expression else if condition then expression «else expression»
or
if condition
  expression
else if condition
  expression

«else
  expression»

or
unless condition
  expression
else unless condition
  expression

«else
  expression»
switch expression
  when condition then expression
  else expression

or
switch expression
  when condition
     expression
  «else
     expression»
All conditions are expressions.
COBOL IF condition «THEN»
  expression
«ELSE
  expression».
[d]
EVALUATE expression «ALSO expression...»
  WHEN case-or-condition «ALSO case-or-condition...»
     expression
  ...

  «WHEN OTHER
     expression»
END-EVALUATE
Rust if condition {
  expression
}« else {
  expression
if condition {
  expression
} else if condition {
  expression
}« else {
  expression
}»
match variable {
  pattern1 => expression,
  pattern2 => expression,
  pattern3 => expression,
  «_ => expression»
}
[b][e]
All conditions are expressions
if else if select case conditional 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 edit

while loop do while loop (count-controlled) for loop foreach
Ada[1] while condition loop
  statements
end loop
loop
  statements
  exit when not condition
end loop
for index in «reverse» [first .. last | discrete_type] loop
  statements
end loop
for item of «reverse» iterator loop
  statements
end loop

or
(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 od for 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) instructions
do instructions while (condition); for («type» i = first; i <= last; i++) instructions
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 condition
  instructions
end

or
until notcondition
  instructions
end
begin
  instructions
end while condition

or
begin
  instructions
end until notcondition
for i in first..last
  instructions
end

or
for i in first...last+1
  instructions
end

or
first.upto(last) { |i| instructions }
for item in set
  instructions
end

or
set.each { |item| instructions }
Bash shell while condition ;do
  instructions
done

or
until notcondition ;do
  instructions
done
for ((i = first; i <= last; ++i)) ; do
  instructions
done
for item in set ;do
  instructions
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:
  loopBlock
loopBlock doWhile:
  conditionBlock
first to: last do:
  loopBlock
collection 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)
Pascal while condition do begin
  instructions
end
repeat
  instructions
until notcondition;
for i := first «step 1» to last do begin
  instructions
end;
[a]
for item in set do instructions
Visual Basic Do While condition
  instructions
Loop

or
Do Until notcondition
  instructions
Loop

or
While condition
  instructions
Wend
(Visual Basic .NET uses End While instead)
Do
  instructions
Loop While condition

or
Do
  instructions
Loop Until notcondition
i must be declared beforehand.

For i = first To last «Step
  instructions

Next i

For Each item In set
  instructions
Next item
Visual Basic .NET For i« As type» = first To last« Step
  instructions

Next« i»
[a]
For Each item« As type» In set
  instructions
Next« item»
Xojo While condition
  instructions
Wend
Do Until notcondition
  instructions
Loop

or
Do
  instructions
Loop Until notcondition
Python while 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-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)
  instructions
ENDDO
DO
  instructions
  IF (condition) EXIT
ENDDO
DO I = first,last
  instructions
ENDDO
Forth BEGIN «instructions» condition WHILE instructions REPEAT BEGIN instructions condition UNTIL limit start DO instructions LOOP
OCaml while condition do instructions done 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
Tab ↹instructions
for i = first to last do
Tab ↹instructions
foritem in set do
Tab ↹instructions

or
Seq.iter (fun item -> instructions) set
Standard ML while condition do ( instructions ) Array.app (fn item => instructions) array
or
app (fn item => instructions) list
Haskell (GHC) Control.Monad.forM_ [first..last] (\i -> do instructions) Control.Monad.forM_list (\item -> do instructions)
Eiffel from
  setup
until
  condition
loop
  instructions
end
CoffeeScript while condition
  expression

or
expression while condition
or
while condition then expression
or
until condition
  expression

or
expression until condition
or
until expression then condition
for i in [first..last]
  expression

or
for i in [first..last] then expression
or
expression for i in [first..last]
for item in set
  expression

or
for item in set then expression
or
expression for item in set
COBOL PERFORM procedure-1 «THROUGH procedure-2» ««WITH» TEST BEFORE» UNTIL condition[c]
or
PERFORM ««WITH» TEST BEFORE» UNTIL condition
  expression
END-PERFORM
PERFORM procedure-1 «THROUGH procedure-2» «WITH» TEST AFTER UNTIL condition[c]
or
PERFORM «WITH» TEST AFTER UNTIL condition
  expression
END-PERFORM
PERFORM procedure-1 «THROUGH procedure-2» VARYING i FROM first BY increment UNTIL i > last[d]
or
PERFORM VARYING i FROM first BY increment UNTIL i > last
  expression
END-PERFORM
[d]
Rust while condition {
  expression
}
loop {
  expression
     if condition {
      break;
  }
}
for i in first..last+1 {
  expression
}

or
for i in first..=last {
  expression
}
for item in set {
  expression
}
[e]
or
set.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 " ") as well as the existential quantifier ("there exists" or " ").
  • ^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 edit

throw handler assertion
Ada[1] raise exception_name «with string_expression» begin
  statements
exception
  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_expression
any_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 { 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 ?
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 ?
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 } ?
Raku try { instructions CATCH { when exception { instructions } ...}} ?
Ruby raise exception begin
  instructions
rescue exception
  instructions
...
«else
  instructions»
«ensure
  instructions»
end
Smalltalk exception raise instructionBlock on: exception do: handlerBlock assert: 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*
)
?
Pascal raise Exception.Create() try Except on E: exception do begin instructions end; end; ?
Visual Basic Err.Raise ERRORNUMBER With New Try: On Error Resume Next
  OneInstruction
.Catch
: On Error GoTo 0: Select Case .Number
  Case SOME_ERRORNUMBER
     instructions
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
Try
  instructions
Catch« name As exception»« When condition»
  instructions
...
«Finally
  instructions»
End Try
System.Diagnostics.Debug.Assert(condition)
or
System.Diagnostics.Trace.Assert(condition)
Xojo Raise exception Try
  instructions
Catch «exception»
  instructions
...
«Finally
  instructions»
End Try
Python raise exception try:
Tab ↹instructions
except «exception»:
Tab ↹instructions
...
«else:
Tab ↹instructions»
«finally:
Tab ↹instructions»
assert condition
Fortran
Forth code THROW xt CATCH ( code or 0 )
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».
Rust No[13] assert!(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 edit

exit block (break) continue label branch (goto) return value from generator
Ada[1] exit «loop_name» «when condition» label: goto label
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
C (C99) break; continue; label: goto label;
Objective-C
C++ (STL)
D
C# yield return value;
Java break «label»; continue «label»;
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»
Bash shell break «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 Basic Exit blockAlternatively, for methods,
Return
label: GoTo label
Xojo Continue block
Visual Basic .NET Yield value
Python break continue yield value
RPG IV LEAVE; ITER;
S-Lang break; continue;
Fortran EXIT CYCLE label[b] GOTO label
Ruby break next
Windows PowerShell break «label» continue
OCaml
F#
Standard ML
Haskell (GHC)
COBOL EXIT PERFORM or EXIT PARAGRAPH or EXIT SECTION or EXIT. EXIT PERFORM CYCLE label «SECTION». GO TO label
  • ^a Pascal has declaration blocks. See functions.
  • ^b label must be a number between 1 and 99999.

Functions edit

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
ALGOL 68 foo «(parameters)»; proc foo = «(parameters)» void: ( instructions ); proc foo = «(parameters)» rettype: ( instructions ...; retvalue );
APL «parameters» foo parameters foo←{ 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)
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; }
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 }
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
)
Pascal foo«(parameters procedure foo«(parameters)»; «forward;»[a]
«label
  label declarations»
«const
  constant declarations»
«type
  type declarations»
«var
  variable declarations»
«local function declarations»

begin
  instructions
end;
function foo«(parameters)»: type; «forward;»[a]
«label
  label declarations»
«const
  constant declarations»
«type
  type declarations»
«var
  variable declarations»
«local function declarations»

begin
  instructions;
  foo := value
end;
program name;
«label
  label declarations»
«const
  constant declarations»
«type
  type declarations»
«var
  variable declarations»
«function declarations»

begin
  instructions
end.
Visual Basic Foo(«parameters») Sub Foo«(parameters
  instructions
End Sub
Function Foo«(parameters)»« As type»
  instructions
  Foo = value
End Function
Sub Main()
  instructions
End Sub
Visual Basic .NET Same as above; alternatively:

Function Foo«(parameters)»« As type»
  instructions
  Return 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»)
  instructions
End Sub
or
Function Main(««ByVal »args() As String») As Integer
  instructions
End Function
Xojo
Python foo(«parameters») def foo(«parameters»):
Tab ↹instructions
def foo(«parameters»):
Tab ↹instructions
Tab ↹return value
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»)
[c]
SUBROUTINE sub_foo («arguments»)
  instructions
END SUBROUTINE
[c]
type FUNCTION foo («arguments»)
  instructions
  ...
  foo = value
END FUNCTION
[c]
PROGRAM main
  instructions
END PROGRAM
Forth «parameters» FOO : FOO « stack effect comment: ( before -- ) »
  instructions
;
: FOO « stack effect comment: ( before -- after ) »
  instructions
;
PHP foo(«parameters») function foo(«parameters») { instructions } function foo(«parameters») { instructions ... return value; }
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«(parameters
  instructions
end
def foo«(parameters
  instructions
  «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 }
Bash shell foo «parameters» function foo {
  instructions
}

or
foo () {
  instructions
}
function foo {
  instructions
  return «exit_code»
}

or
foo () {
  instructions
  return «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
Tab ↹instructions
foo parameters = return_value
or
foo parameters = do
Tab ↹instructions
Tab ↹return value
«main :: IO ()»
main = do instructions
Eiffel foo («parameters») foo («parameters»)
  require
     preconditions
  do
     instructions
  ensure
     postconditions
  end
foo («parameters»): type
  require
     preconditions
  do
     instructions
     Result := value
  ensure
     postconditions
  end
[b]
CoffeeScript foo() foo = -> foo = -> value
foo parameters foo = () -> foo = ( parameters ) -> value
COBOL CALL "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. 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.
  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 edit

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);
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}`
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)
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>))
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;
Perl[b] 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)[c] TO number MOVE number TO numeric-edited
  • ^a JavaScript only uses floating point numbers so there are some technicalities.[7]
  • ^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 edit

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));[a]
APL x← ⎕←x ⍞←x
C (C99) scanf(format, &x);
or
fscanf(stdin, format, &x);[b]
printf(format, x);
or
fprintf(stdout, format, x);[c]
fprintf(stderr, format, x);[d]
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(os.Stderr, x)
or
fmt.Fprintf(os.Stderr, 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
(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)
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
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)
print >> sys.stderr, 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 names[e]
WRITE(*,format) expressions
or
WRITE(OUTPUT_UNIT,format) expressions[e]
WRITE(ERROR_UNIT,format) expressions[e]
Forth buffer length ACCEPT ( # chars read )
KEY ( char )
buffer length TYPE
char EMIT
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 TextIO.output (TextIO.stdErr, 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
  • ^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.[15]

Reading command-line arguments edit

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
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()
Swift Process.arguments[n] or
Process.unsafeArgv[n]
Process.arguments.count or
Process.argc
first argument
Common Lisp ? ? ?
Scheme (R6RS) (list-ref (command-line) n) (length (command-line)) first argument
ISLISP
Pascal ParamStr(n) ParamCount first argument
Visual Basic Command[b] 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,argc
  CALL 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 List.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 edit

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)
D std.process.system("command"); std.process.execv(path, arglist);
Java Runtime.exec(command);
or
new ProcessBuilder(command).start();
JavaScript
Windows Script Host implementation
WScript.CreateObject ("WScript.Shell").Run(command «, WindowStyle» «, isWaitOnReturn»); WshShell.Exec(command)
Common Lisp (uiop:run-program command)
Scheme (system command)
ISLISP
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»)[a]
Windows PowerShell [Diagnostics.Process]::Start(command) «Invoke-Item »program arg1 arg2 ...
Bash shell output=`command`
or
output=$(command)
program arg1 arg2 ...

^a Fortran 2008 or newer.[17]

References edit

  1. ^ a b c d e f g h i j k l m n o p Ada Reference Manual – Language and Standard Libraries; ISO/IEC 8652:201x (E), (PDF). Archived from the original (PDF) on 2011-04-27. Retrieved 2013-07-19.
  2. ^ "Common Lisp HyperSpec (TM)". lispworks.com. Retrieved 30 January 2017.
  3. ^ . islisp.info. Archived from the original on 22 January 2016. Retrieved 30 January 2017.
  4. ^ a b "selected_int_kind in Fortran Wiki". fortranwiki.org. Retrieved 30 January 2017.
  5. ^ "Erlang — Types and Function Specifications". erlang.org. Retrieved 30 January 2017.
  6. ^ "Erlang — Advanced". erlang.org. Retrieved 30 January 2017.
  7. ^ a b 8.5 The Number Type
  8. ^ a b "selected_real_kind in Fortran Wiki". fortranwiki.org. Retrieved 30 January 2017.
  9. ^ "The GNU C Library: Complex Numbers". gnu.org. Retrieved 30 January 2017.
  10. ^ "Grammar vb". Visual Basic Language Specification. 2016-06-17. from the original on 2019-08-29. Retrieved 2019-08-29.
  11. ^ "for...of". mozilla.org. Retrieved 30 January 2017.
  12. ^ . google.com. Archived from the original on 16 April 2016. Retrieved 30 January 2017.
  13. ^ Klabnik, Steve; Nichols, Carol. "Error Handling". The Rust Programming Language.
  14. ^ "Prime decomposition – Rosetta Code". rosettacode.org. Retrieved 30 January 2017.
  15. ^ "iso_fortran_env in Fortran Wiki". fortranwiki.org. Retrieved 30 January 2017.
  16. ^ "Execute a system command – Rosetta Code". rosettacode.org. Retrieved 30 January 2017.
  17. ^ "EXECUTE_COMMAND_LINE – The GNU Fortran Compiler". gnu.org. Retrieved 30 January 2017.

comparison, programming, languages, basic, instructions, this, article, needs, additional, citations, verification, please, help, improve, this, article, adding, citations, reliable, sources, unsourced, material, challenged, removed, find, sources, comparison,. This article needs additional citations for verification Please help improve this article by adding citations to reliable sources Unsourced material may be challenged and removed Find sources Comparison of programming languages basic instructions news newspapers books scholar JSTOR February 2009 Learn how and when to remove this message 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 Contents 1 Conventions of this article 2 Type identifiers 2 1 Integers 2 2 Floating point 2 3 Complex numbers 2 4 Other variable types 3 Derived types 3 1 Array 3 2 Other types 4 Variable and constant declarations 5 Control flow 5 1 Conditional statements 5 2 Loop statements 5 3 Exceptions 5 4 Other control flow statements 6 Functions 7 Type conversions 8 Standard stream I O 9 Reading command line arguments 10 Execution of commands 11 ReferencesConventions of this article editGenerally 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 editIntegers edit 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 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 wbr wbr Size 1 j or mod Integer wbr wbr 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 t uint8 t int16 t uint16 t int32 t uint32 t int64 t uint64 t intptr t c size t c C C 11 fixed width C C99 variable width signed char unsigned char short 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 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 wbr wbr BigInteger NET 4 0 Java byte char b java math wbr wbr 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 Swift Int8 UInt8 Int16 UInt16 Int32 UInt32 Int64 UInt64 Int UInt D byte ubyte short ushort int uint long ulong 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 Visual Basic Byte Integer Long Visual Basic NET SByte Short UShort Integer UInteger Long ULong System Numerics wbr wbr BigInteger NET 4 0 FreeBasic Byte or Integer lt 8 gt UByte or UInteger lt 8 gt Short or Integer lt 16 gt UShort or UInteger lt 16 gt Long or Integer lt 32 gt ULong or UInteger lt 32 gt LongInt or Integer lt 64 gt ULongInt or UInteger lt 64 gt Integer UInteger Python 2 x int long Python 3 x int S Lang Fortran INTEGER wbr wbr KIND n f INTEGER wbr wbr KIND n f INTEGER wbr wbr KIND n f INTEGER wbr wbr KIND n f PHP int m int m e Perl 5 d d d d d Math BigInt Raku int8 uint8 int16 uint16 int32 uint32 int64 uint64 Int Ruby Fixnum Bignum Erlang n integer integer o Scala Byte Short Char l Int Long scala math BigInt Seed7 integer bigInteger Smalltalk SmallInteger i LargeInteger i Windows PowerShell OCaml int32 int64 int or nativeint open Big int or big int F sbyte byte int16 uint16 int32 or int uint32 uint64 nativeint unativeint bigint Standard ML Word8 word Int32 int Word32 word Int64 int Word64 word int word LargeInt 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 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 COBOL h BINARY CHAR SIGNED BINARY CHAR UNSIGNED BINARY SHORT SIGNED BINARY SHORT UNSIGNED BINARY LONG SIGNED BINARY LONG UNSIGNED BINARY DOUBLE SIGNED BINARY DOUBLE UNSIGNED Mathematica Integer Wolfram Language Integer 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 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 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 KIND 4 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 edit Single precision Double precision Other precision Processor dependent Ada 1 Float Long Float ALGOL 68 real a long real a short real long long real etc d C float b double long double f C STL Objective C Cocoa CGFloat C float Java Go float32 float64 Rust f32 f64 Swift Float or Float32 Double or Float64 Float80 g 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 Visual Basic NET Xojo Python float JavaScript Number 7 S Lang Fortran REAL KIND n c PHP float Perl Raku num32 num64 Num Ruby Float Scala Float Double Seed7 float Smalltalk Float Double Windows PowerShell OCaml float F float32 Standard ML real Haskell GHC Float Double Eiffel REAL 32 REAL 64 COBOL FLOAT BINARY 7 e FLOAT BINARY 34 e FLOAT SHORT FLOAT LONG FLOAT EXTENDED Mathematica Real 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 KIND 8 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 edit Integer Single precision Double precision Half and Quadruple precision etc Ada 1 Complex b Complex b Complex b ALGOL 68 compl long compl etc short compl etc and long long compl etc C C99 9 float complex double complex C STL std complex lt float gt std complex lt double gt C System Numerics Complex NET 4 0 Java Go complex64 complex128 D cfloat cdouble Objective C Common Lisp complex integer complex single float complex double float complex Scheme Pascal Visual Basic Visual Basic NET System Numerics Complex NET 4 0 Perl Math Complex Raku complex64 complex128 Complex Python complex JavaScript S Lang Fortran COMPLEX KIND n a Ruby Complex Complex Scala Seed7 complex Smalltalk Complex Complex Complex Windows PowerShell OCaml Complex t F System Numerics Complex NET 4 0 Standard ML Haskell GHC Complex Complex Float Complex Complex Double Eiffel COBOL Mathematica Complex Complex a The value of n is provided by the SELECTED REAL KIND 8 intrinsic function b Generic type which can be instantiated with any base floating point type Other variable types edit Text Boolean Enumeration Object Universal Character String a Ada 1 Character String Bounded String Unbounded String Boolean i item sub 1 sub i i item sub 2 sub i i i tagged null record ALGOL 68 char string bytes bool bits User defined C C99 char wchar t bool b enum i name i i item sub 1 sub i i item sub 2 sub i i i a href Void type html title Void type void a a href Pointer computer programming html title Pointer computer programming a C STL std string Objective C unichar NSString BOOL id C char string bool enum i name i i item sub 1 sub i i value i i item sub 2 sub i i value i i i object Java String boolean enum i name i i item sub 1 sub i i item sub 2 sub i i i Object Go byte rune string bool const br span class nowrap span i item sub 1 sub i i iota i br span class nowrap span i item sub 2 sub i br span class nowrap span i i br interface Rust char String bool enum i name i i item sub 1 sub i i value i i item sub 2 sub i i value i i i std any Any Swift Character String Bool enum i name i case i item sub 1 sub i i item sub 2 sub i i i Any D char string bool enum i name i i item sub 1 sub i i item sub 2 sub i i i std variant Variant Common Lisp character string boolean member i item sub 1 sub i i item sub 2 sub i i i t Scheme ISLISP Pascal ISO char boolean i item sub 1 sub i i item sub 2 sub i i i Object Pascal Delphi string variant Visual Basic String Boolean Enum i name i br span class nowrap span i item sub 1 sub i i value i br span class nowrap span i item sub 2 sub i i value br span class nowrap span i br End Enum Variant type Variant Visual Basic NET Char Object Xojo Object or Variant Python d str bool from enum import Enum br class Name Enum br span class nowrap span i item sub 1 sub i i value i br span class nowrap span i item sub 2 sub i i value i br span class nowrap span i i object JavaScript d String Boolean Object S Lang Fortran CHARACTER LEN CHARACTER LEN allocatable LOGICAL KIND n f CLASS PHP d string bool type declaration omitted Perl d UNIVERSAL Raku Char Str Bool enum i name lt item sub 1 sub item sub 2 sub gt i enum i name lt lt item sub 1 sub value item sub 2 sub value gt gt i Mu Ruby d String Object c Object Scala Char String Boolean object i name i extends Enumeration br span class nowrap span i val item sub 1 sub item sub 2 sub Value i br Any Seed7 char string boolean const type i name i is new enum br span class nowrap span i item sub 1 sub i br span class nowrap span i item sub 2 sub i br span class nowrap span i i br end enum Windows PowerShell OCaml char string bool e F type i name i i item sub 1 sub i i value i i item sub 2 sub i i value i i i obj Standard ML e Haskell GHC Char String Bool e Eiffel CHARACTER STRING BOOLEAN ANY COBOL PIC X i PIC X i string length i i or PIC X X i PIC 1 i number of digits i i 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 KIND 4 intrinsic function Derived types editArray edit Further information Comparison of programming languages array fixed size array dynamic size array one dimensional array multidimensional array one dimensional array multidimensional array Ada 1 array i lt first gt i i lt last gt i of i lt type gt i orarray i lt discrete type gt i of i lt type gt i array i lt first sub 1 sub gt i i lt last sub 1 sub gt i i lt first sub 2 sub gt i i lt last sub 2 sub gt i i i of i lt type gt i orarray i lt discrete type sub 1 sub gt i i lt discrete type sub 2 sub gt i i i of i lt type gt i array i lt discrete type gt i range lt gt of i lt type gt i array i lt discrete type sub 1 sub gt i range lt gt i lt discrete type sub 2 sub gt i range lt gt i i of i lt type gt i ALGOL 68 i first i i last i wbr wbr modename or simply i size i wbr wbr modename i first sub 1 sub i i last sub 1 sub i i first sub 2 sub i i last sub 2 sub i wbr wbr modename or i first sub 1 sub i i last sub 1 sub i i first sub 2 sub i i last sub 2 sub i wbr wbr modename etc flex i first i i last i wbr wbr modename or simply flex i size i wbr wbr modename flex i first sub 1 sub i i last sub 1 sub i i first sub 2 sub i i last sub 2 sub i wbr wbr modename orflex i first sub 1 sub i i last sub 1 sub i wbr wbr flex i first sub 2 sub i i last sub 2 sub i wbr wbr modename i etc i C C99 i type name i i size i a i type name i i size sub 1 sub i i size sub 2 sub i a i type i i name i or within a block i int n type name i i n i C STL a href Std array html class mw redirect title Std array std array a lt i type size i gt C 11 a href Std vector html class mw redirect title Std vector std vector a lt i type i gt C i type i i type i i i System wbr wbr Collections wbr wbr ArrayListorSystem wbr wbr Collections wbr wbr Generic wbr wbr List wbr wbr lt i type i gt Java i type i b i type i i i b ArrayList i or i ArrayList lt i type i gt D i type i i size i i type i i size sub 1 sub i i size sub 2 sub i i type i Go i size i i type i i size sub 1 sub i i size sub 2 sub i i type i type type Rust i type size i i type size sub 1 sub i i size sub 2 sub i Vec lt i type i gt Vec lt Vec lt i type i gt gt Swift i type i or Array lt i type i gt i type i or Array lt Array lt i type i gt gt Objective C NSArray NSMutableArray JavaScript Array d Common Lisp simple array type dimension simple array type dimension1 dimension2 array type dimension array type dimension1 dimension2 Scheme ISLISP Pascal array i first i i last i of i type i c array i first sub 1 sub i i last sub 1 sub i of array i first sub 2 sub i i last sub 2 sub i i i of i type i c orarray i first sub 1 sub i i last sub 1 sub i i first sub 2 sub i i last sub 2 sub i i i of i type i c Object Pascal Delphi array of i type i array of array i i of i type i Visual Basic Dim x i last i As i type i Dim x i last sub 1 sub i i last sub 2 sub i i i As i type i Visual Basic NET i type i i type i i i System wbr wbr Collections wbr wbr ArrayListorSystem wbr wbr Collections wbr wbr Generic wbr wbr List wbr wbr Of i type i Python list S Lang x i type i i size i x i type i i size sub 1 sub i i size sub 2 sub i i i Fortran i type i i name i i size i i type i i name i i size i sub 1 sub i size sub 2 sub i i type i ALLOCATABLE i name i i type i ALLOCATABLE i name i PHP array Perl Raku Array i type i i or i Array of i type i Ruby x Array new i size sub 1 sub i Array new i size sub 2 sub i Array Scala Array i type i Array i i Array i type i i i ArrayBuffer i type i Seed7 array i type i orarray i idxType i i type i array array i type i orarray i idxType i array i idxType i i type i array i type i orarray i idxType i i type i array array i type i orarray i idxType i array i idxType i i type i Smalltalk Array OrderedCollection Windows PowerShell i type i i type i i i OCaml i type i array i type i array i i array F i type i or i type i array i type i i i System wbr wbr Collections wbr wbr ArrayListorSystem wbr wbr Collections wbr wbr Generic wbr wbr List wbr wbr lt i type i gt Standard ML i type i vector i or type i array Haskell GHC x Array array 0 i size i 1 i list of association pairs i x Array array 0 0 i i i size sub 1 sub i 1 i size sub 2 sub i 1 i i i list of association pairs i COBOL i level number type i OCCURS i size i TIMES one dimensional array definition i level number type i OCCURS i min size i TO i max size i TIMES DEPENDING ON i size i e a In most expressions except the a href Sizeof html title Sizeof sizeof a and amp 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 i type i x works in Java however i type i 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 edit Simple composite types Algebraic data types Unions Records Tuple expression Ada 1 type i name i is abstract tagged limited i i record br i field sub 1 sub i i type i br i field sub 2 sub i i type i br i i br end record i i null record i i Any combination of records unions and enumerations as well as references to those enabling recursive types type i name i i variation i i discrete type i is record br case i variation i is br when i choice list sub 1 sub i gt br i fieldname sub 1 sub i i type i br i i br when i choice list sub 2 sub i gt br i fieldname sub 2 sub i i type i br i i br i i br end case br end record ALGOL 68 struct i i modename i fieldname i i i Required types and operators can be user defined union i i modename i i i i C C99 struct i name i i type name i i i union i type name i i i Objective C C struct i name i i type name i i i b a href C 2B 2B11 html Tuple types title C 11 std tuple a lt i type sub 1 sub type sub n sub i gt C struct i name i i type name i i i i val sub 1 sub i i val sub 2 sub i i i Java a JavaScript D struct i name i i type name i i i std variant Algebraic i type i union i type name i i i Go struct br i name type i br i i br Rust struct name i name i type i i i val sub 1 sub i i val sub 2 sub i i i enum name i Foo i i types i i i union name i name i type i i Swift struct i name i i br i var i name i i type br br i i name sub 1 sub i i val sub 1 sub i i name sub 2 sub i i val sub 2 sub i i name sub 3 sub i i val sub 3 sub i i i enum i name i case i Foo i i types i case i Bar i i types i i i Common Lisp defstruct name slot name slot name initial value slot name initial value type type cons i val sub 1 sub val sub 2 sub i c Scheme ISLISP Pascal record br i name i i type i br i br i end record br case i type i of br i value i i types i br i i br end Visual Basic Visual Basic NET Structure i name i br Dim i name i As i type i br i i br End Structure i val sub 1 sub i i val sub 2 sub i i i Python a i val sub 1 sub i i val sub 2 sub i i val sub 3 sub i i i S Lang struct i name value i Fortran TYPE i name br type i i name br br i END TYPE PHP a Perl d Raku a Ruby span class no OpenStruct span span class o span span class n new span span class p span span class ss name span span class w span span class o gt span span class w span span class n value span span class p span Scala case class i name i i var i i name i i type i i i i val sub 1 sub i i val sub 2 sub i i val sub 3 sub i i i abstract class i name i br case class i Foo i i parameters i extends i name i br case class i Bar i i parameters i extends i name i br i i orabstract class i name i br case object i Foo i extends i name i br case object i Bar i extends i name i br i i or a combination of case classes and case objects Windows PowerShell OCaml type i name i i mutable i i name i i type i i i i val sub 1 sub i i val sub 2 sub i i val sub 3 sub i i i type i name i i Foo i of i type i i Bar i of i type i i i F Standard ML type i name i i name i i type i i i i val sub 1 sub i i val sub 2 sub i i val sub 3 sub i i i datatype i name i i Foo i of i type i i Bar i of i type i i i Haskell data i Name i i Constr i i name i i type i i i data i Name i i Foo i i types i i Bar i i types i i i COBOL i level number name type clauses i br i level number n name type clauses i br i i i name i REDEFINES i variable type i 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 constructorsVariable and constant declarations editvariable constant type synonym Ada 1 i identifier i i type i i initial value i e i identifier i constant i type i i final value i subtype i identifier i is i type i ALGOL 68 modename name i initial value i modename name i value i a href Typedef html title Typedef mode a synonym modename C C99 i type name i i initial value i enum i name i i value i a href Typedef html title Typedef typedef a i type synonym i Objective C C const i type name i i value i C i type name sub 1 sub i i initial value i i name sub 2 sub i i initial value i i i orvar i name i i initial value i const i type name i i value i i name i i value i i i orreadonly i type name i i value i i name i i value i i i using i synonym i i type i D i type name i i initial value i orauto i name i i value i const i type name i i value i orimmutable i type name i i value i alias i type synonym i Java i type name i i initial value i final i type name i i value i JavaScript var i name i i initial value i orlet i name i i initial value i since ECMAScript 2015 const i name i i value i since ECMAScript 2015 Go var i name type i i initial value i or i name i i initial value i const i name type i i value i type i synonym type i Rust f let mut i name i i type i i initial value i static mut i NAME i i type i i value i let i name i i type i i initial value i const i NAME i i type i i value i static i NAME i i type i i value i type i synonym i i typename i Swift var i name i i type i i initial value i let i name i i type i i value i typealias i synonym i i type i Common Lisp defparameter i name initial value i or defvar i name initial value i defconstant i name value i deftype i synonym i i type i Scheme define i name initial value i ISLISP defglobal i name initial value i or defdynamic i name initial value i defconstant i name value i Pascal a i name i i type i i initial value i i name i i value i i synonym i i type i Visual Basic Dim i name i As i type i See notes to left Constants use the same syntax and use Const instead of Dim have a restriction to only certain primitive typesConst i name sub 1 sub i As i type i i value i i name sub 2 sub i As i type i i value i 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 i identifier i As i object creation expression i object initializer declarator i modified identifier i As i non array type i i array rank specifier i i initial value i single declarator or i modified identifier list i As i non array type i i array rank specifier i multiple declarator valid declaration statements are of the form Dim i declarator list i 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 i type i of each object initializer declarator is replaced with As i type i New i type i 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 i synonym i i type i Xojo Dim i name i As i type i i initial value i Python i name type i i initial value i i synonym i i type i b CoffeeScript i name i i initial value i S Lang i name i i initial value i typedef struct i typename i Fortran type name i type i PARAMETER i name i i value i PHP i name i i initial value i define i name i i value i br const i name i i value 5 3 i Perl my i name i i initial value i c use constant i name i gt i value i Raku my i type i i name i i initial value i c my i type i constant i name i i value i i synonym i i type i Ruby i name i i initial value i i Name i i value i i synonym i i type i b Scala var i name i i type i i initial value i val i name i i type i i value i type i synonym i i type i Windows PowerShell i type i i name i i initial value i Bash shell name i initial value i OCaml let i name i i type i ref ref i value i d let i name i i type i i value i type i synonym i i type i F let mutable i name i i type i i value i Standard ML val i name i i type i ref ref i value i d val i name i i type i i value i Haskell i name i i type i i name i i value i type i Synonym i i type i Forth VARIABLE i name i in some systems use i value i VARIABLE i name i instead i value i CONSTANT i name i COBOL i level number name type clauses i 0 1 i name i CONSTANT AS i value i i level number name type clauses i IS TYPEDEF Mathematica name i initial value i 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 editConditional statements edit if else if select case conditional expression Ada 1 if i condition i then br i statements i br else br i statements i br end if if i condition sub 1 sub i then br i statements i br elsif i condition sub 2 sub i then br i statements i br i i br else br i statements i br end if case i expression i is br when i value list i sub 1 sub gt i statements i br when i value list sub 2 sub i gt i statements i br i i br when others gt i statements i br end case if i condition sub 1 sub i then br i expression sub 1 sub i br elsif i condition sub 2 sub i then br i expression sub 2 sub i br i i br else br i expression sub n sub i br or case i expression i is br when i value list sub 1 sub i gt i expression sub 1 sub i br when i value list sub 2 sub i gt i expression sub 2 sub i br i i br when others gt i expression sub n sub i br Seed7 if i condition i then br i statements i br else br i statements i br end if if i condition sub 1 sub i then br i statements i br elsif i condition sub 2 sub i then br i statements i br i i br else br i statements i br end if case i expression i of br when i set1 i i statements i br i i br otherwise i statements i br end case Modula 2 if i condition i then br i statements i br else br i statements i br end if i condition sub 1 sub i then br i statements i br elsif i condition sub 2 sub i then br i statements i br i i br else br i statements i br end case i expression i of br i caseLabelList i i statements i br i i br else i statements i br end ALGOL 68 if i condition i then i statements i else i statements i fi if i condition i then i statements i elif i condition i then i statements i fi case i switch i in i statements statements i out i statements i esac condition valueIfTrue valueIfFalse ALGOL 68 brief form condition statements statements condition statements condition statements variable statements statements APL If i condition i br i instructions i br Else br i instructions i br EndIf If i condition i br i instructions i br ElseIf i condition i br i instructions i br i i br Else br i instructions i br EndIf Select i expression i br Case i case1 i br i instructions i br i i br Else br i instructions i br EndSelect i condition i i valueIfTrue i i valueIfFalse i C C99 if i condition i i instructions i br else i instructions i instructions can be a single statement or a block in the form of i statements i if i condition i i instructions i br else if i condition i i instructions i br i i br else i instructions i orif i condition i i instructions i br else if i condition i i instructions i switch i variable i br case i case1 i i instructions i break br i i br default i instructions i br i condition i a href 3F html class mw redirect title a i valueIfTrue i a href 3F html class mw redirect title a i valueIfFalse i Objective C C STL D Java JavaScript PHP C if i condition i i instructions i br else i instructions i instructions can be a single statement or a block in the form of i statements i if i condition i i instructions i br else if i condition i i instructions i br i i br else i instructions i switch i variable i br br case i case sub 1 sub i br i instructions i br i break or jump statement i br i i br default br i instructions i br i break or jump statement i br 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 i condition i a href 3F html class mw redirect title a i valueIfTrue i a href 3F html class mw redirect title a i valueIfFalse i Windows PowerShell if i condition i i instruction i br else i instructions i if i condition i i instructions i br elseif i condition i i instructions i br i i br else i instructions i switch i variable i i case1 i i instructions i break i i default i instructions i Go if i condition i i instructions i br else i instructions i if i condition i i instructions i br else if i condition i i instructions i br i i br else i instructions i orswitch br case i condition i i instructions i br i i br default i instructions i br switch i variable i br case i case sub 1 sub i i instructions i br i i br default i instructions i br Swift if i condition i i instructions i br else i instructions i if i condition i i instructions i br else if i condition i i instructions i br i i br else i instructions i switch i variable i br case i case sub 1 sub i i instructions i br i i br default i instructions i br Perl if i condition i i instructions i br else i instructions i orunless i notcondition i i instructions i br else i instructions i if i condition i i instructions i br elsif i condition i i instructions i br i i br else i instructions i orunless i notcondition i i instructions i br elsif i condition i i instructions i br i i br else i instructions i use feature switch br i i br given i variable i br when i case sub 1 sub i i instructions i br i i br default i instructions i br i condition i a href 3F html class mw redirect title a i valueIfTrue i a href 3F html class mw redirect title a i valueIfFalse i Raku if i condition i i instructions i br else i instructions i orunless i notcondition i i instructions i if i condition i i instructions i br elsif i condition i i instructions i br br else i instructions i given i variable i br when i case sub 1 sub i i instructions i br i i br default i instructions i br i condition i a href 3F html class mw redirect title a i valueIfTrue i i valueIfFalse i Ruby if i condition i br i instructions i br else br i instructions i if i condition i br i instructions i br elsif i condition i br i instructions i br i i br else br i instructions i br end case i variable i br when i case sub 1 sub i br i instructions i br i i br else br i instructions i br end i condition i a href 3F html class mw redirect title a i valueIfTrue i a href 3F html class mw redirect title a i valueIfFalse i Scala if i condition i i instructions i br else i instructions i if i condition i i instructions i br else if i condition i i instructions i br br else i instructions i i expression i match br case i pattern1 i gt i expression i br case i pattern2 i gt i expression i br i i br case gt i expression i br b if i condition i i valueIfTrue i else i valueIfFalse i Smalltalk i condition i ifTrue br i trueBlock i br ifFalse br i falseBlock i br end i condition i ifTrue i trueBlock i ifFalse i falseBlock i Common Lisp i when i condition br i instructions i or unless i condition i br i instructions i or if i condition i br progn i instructions i br progn i instructions i cond i condition1 instructions i br i condition2 instructions i br i i br t i instructions i case i expression i br i case1 instructions i br i case2 instructions i br i i br otherwise i instructions i if i test then else i or cond i test1 value1 i i test2 value2 i i i Scheme when i condition instructions i or if i condition i begin i instructions i begin i instructions i cond i condition1 instructions i i condition2 instructions i i i else i instructions i case i variable i i case1 i i instructions i i case2 i i instructions i i i else i instructions i if i condition valueIfTrue valueIfFalse i ISLISP if i condition i br progn i instructions i br progn i instructions i cond i condition1 instructions i br i condition2 instructions i br i i br t i instructions i case i expression i br i case1 instructions i br i case2 instructions i br i i br t i instructions i if i condition valueIfTrue valueIfFalse i Pascal if i condition i then begin br i instructions i br end br else begin br i instructions i br end c if i condition i then begin br i instructions i br end br else if i condition i then begin br i instructions i br end br i i br else begin br i instructions i br end c case i variable i of br i case1 i i instructions i br i i br else i instructions i br end c Visual Basic If i condition i Then br i instructions i br Else br i instructions i br End IfSingle line when instructions are instruction sub 1 sub instruction sub 2 sub If i condition i Then i instructions i Else i instructions i If i condition i Then br i instructions i br ElseIf i condition i Then br i instructions i br i i br Else br i instructions i br 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 i variable i br Case i case pattern sub 1 sub i br i instructions i br i i br Case Else br i instructions i br End Select a href IIf html title IIf IIf a i condition i i valueIfTrue i i valueIfFalse i Visual Basic NET If i condition i i valueIfTrue i i valueIfFalse i Xojo Python a if i condition i br kbd class keyboard key nowrap Tab kbd i instructions i br else br kbd class keyboard key nowrap Tab kbd i instructions i if i condition i br kbd class keyboard key nowrap Tab kbd i instructions i br elif i condition i br kbd class keyboard key nowrap Tab kbd i instructions i br i i br else br kbd class keyboard key nowrap Tab kbd i instructions i Python 3 10 match i variable i br kbd class keyboard key nowrap Tab kbd case i case1 i br kbd class keyboard key nowrap Tab kbd kbd class keyboard key nowrap Tab kbd i instructions i br kbd class keyboard key nowrap Tab kbd case i case2 i br kbd class keyboard key nowrap Tab kbd kbd class keyboard key nowrap Tab kbd i instructions i Python 2 5 i valueIfTrue i if i condition i else i valueIfFalse i S Lang if i condition i i instructions i else i instructions i if i condition i i instructions i else if i condition i i instructions i i i else i instructions i switch i variable i case i case1 i i instructions i case i case2 i i instructions i i i Fortran IF i condition i THEN br i instructions i br ELSE br i instructions i br ENDIF IF i condition i THEN br i instructions i br ELSEIF i condition i THEN br i instructions i br i i br ELSE br i instructions i br ENDIF SELECT CASE i variable i br CASE i case1 i br i instructions i br i i br CASE DEFAULT br i instructions i br END SELECT Forth i condition i IF i instructions i ELSE i instructions i THEN i condition i IF i instructions i ELSE i condition i IF i instructions i THEN THEN i value i CASE br i case i OF i instructions i ENDOF br i case i OF i instructions i ENDOF br i default instructions i br ENDCASE i condition i IF i valueIfTrue i ELSE i valueIfFalse i THEN OCaml if i condition i then begin i instructions i end else begin i instructions i end if i condition i then begin i instructions i end else if i condition i then begin i instructions i end i i else begin i instructions i end match i value i with br i pattern1 i gt i expression i br i pattern2 i gt i expression i br i i br gt i expression i b if i condition i then i valueIfTrue i else i valueIfFalse i F Lightweight syntax mode Either on a single line or with indentation as shown below if i condition i then br kbd class keyboard key nowrap Tab kbd i instructions i br else br kbd class keyboard key nowrap Tab kbd i instructions i Verbose syntax mode Same as Standard ML Lightweight syntax mode Either on a single line or with indentation as shown below if i condition i then br kbd class keyboard key nowrap Tab kbd i instructions i br elif i condition i then br kbd class keyboard key nowrap Tab kbd i instructions i br i i br else br kbd class keyboard key nowrap Tab kbd i instructions i Verbose syntax mode Same as Standard ML Standard ML if i condition i then i instructions i br else i instructions i if i condition i then i instructions i br else if i condition i then i instructions i br i i br else i instructions i case i value i of br i pattern1 i gt i expression i br i pattern2 i gt i expression i br i i br gt i expression i b Haskell GHC if i condition i then i expression i else i expression i orwhen i condition i do i instructions i orunless i notcondition i do i instructions i i result i i condition i i expression i br i condition i i expression i br otherwise i expression i case i value i of br i pattern1 i gt i expression i br i pattern2 i gt i expression i br i i br gt i expression i br b Bash shell if i condition command i then br i expression i br else br i expression i br fi if i condition command i then br i expression i br elif i condition command i then br i expression i br else br i expression i br fi case i variable i in br i condition1 br command br condition2 br command i br esac CoffeeScript if i condition i then i expression i else i expression i orif i condition br expression i br else br i expression i or i expression i if i condition i orunless i condition i br i expression i br else br i expression i or i expression i unless i condition i if i condition i then i expression i else if i condition i then i expression i else i expression i orif i condition i br i expression i br else if i condition br expression i br else br i expression i orunless i condition i br i expression i br else unless i condition br expression i br else br i expression i switch i expression i br when i condition i then i expression i br else i expression i orswitch i expression i br when i condition i br i expression i br else br i expression i All conditions are expressions COBOL IF i condition i THEN br i expression i br ELSE br i expression i d EVALUATE i expression i ALSO i expression i br WHEN i case or condition i ALSO i case or condition br expression br i br WHEN OTHER br i expression i br END EVALUATE Rust if i condition i br i expression i br else br i expression i br if i condition i br i expression i br else if i condition i i br expression br i else i br expression br i i i match i variable i br i pattern1 i gt i expression i br i pattern2 i gt i expression i br i pattern3 i gt i expression i br gt i expression i br b e All conditions are expressions if else if select case conditional 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 edit while loop do while loop count controlled for loop foreach Ada 1 while i condition i loop br i statements i br end loop loop br i statements i br exit when not i condition i br end loop for i index i in reverse i first i i last discrete type i loop br i statements i br end loop for i item i of reverse i iterator i loop br i statements i br end loopor for all some in of i first i i last discrete type iterator i gt i predicate i b ALGOL 68 for i index i from i first i by i increment i to i last i while i condition i do i statements i od for key to upb list do typename val list key i statements i od while i condition i br do i statements i od while i statements condition i br do i statements i od for i index i from i first i by i increment i to i last i do i statements i od APL While i condition i br i statements i br EndWhile Repeat br i statements i br Until i condition i For i var s i In i list i br i statements i br EndFor For i var s i InEach i list i br i statements i br EndFor C C99 instructions can be a single statement or a block in the form of i statements i while i condition i i instructions i do i instructions i while i condition i for i type i i i first i i i i lt i last i i i i i instructions i Objective C for i type item i in i set i i instructions i C STL std for each i start i i end i i function i Since C 11 for i type item i i set i i instructions i C foreach i type item i in i set i i instructions i Java for i type item i i set i i instructions i JavaScript for var i i i i first i i i i lt i last i i i i i instructions i Since EcmaScript 2015 11 for var i item i of i set i i instructions i PHP foreach range i first i i last i as i i instructions i orfor i i first i i lt i last i i i instructions i foreach i set i as i item i i instructions i orforeach i set i as i key i gt i item i i instructions i Windows PowerShell for i i first i i le i last i i i instructions i foreach i item i in i set i i instructions i D foreach i i i first i i last i instructions i foreach i type item set instructions i Go for i condition i i instructions i for i i i i first i i i i lt i last i i i i i instructions i for i key i i item i range i set i i instructions i Swift while i condition i i instructions i 2 x repeat i instructions i while i condition i 1 x do i instructions i while i condition i for i i i i first i i last i i instructions i orfor i i i i first i lt i last 1 i i instructions i orfor var i i i i first i i i i lt i last i i i i i instructions i for i item i in i set i i instructions i Perl while i condition i i instructions i oruntil i notcondition i i instructions i do i instructions i while i condition i ordo i instructions i until i notcondition i for each i i first i i last i i instructions i orfor i i first i i lt i last i i i instructions i for each i item i i set i i instructions i Raku while i condition i i instructions i oruntil i notcondition i i instructions i repeat i instructions i while i condition i orrepeat i instructions i until i notcondition i for i first i i last i gt i i instructions i orloop i i first i i lt i last i i i instructions i for i set i gt i item i i instructions i Ruby while i condition i br i instructions i br endoruntil i notcondition i br i instructions i br end begin br i instructions i br end while i condition i orbegin br i instructions i br end until i notcondition i for i in i first i i last i br i instructions i br endorfor i in i first i i last 1 i br i instructions i br endor i first i upto i last i i i instructions i for i item i in i set i br i instructions i br endor i set i each i item i i instructions i Bash shell while i condition i do br i instructions i br doneoruntil i notcondition i do br i instructions i br done for i i i i first i i i i lt i last i i i i do br i instructions i br done for i item i in i set i do br i instructions i br done Scala while i condition i i instructions i do i instructions i while i condition i for i i i lt i first i to i last i by 1 i instructions i or i first i to i last i by 1 foreach i i i gt i instructions i for i item i lt i set i i instructions i or i set i foreach i item i gt i instructions i Smalltalk i conditionBlock i whileTrue br i loopBlock i i loopBlock i doWhile br i conditionBlock i i first i to i last i do br i loopBlock i i collection i do br i loopBlock i Common Lisp loop br while i condition i br do br i instructions i or do i notcondition i br i instructions i loop br do br i instructions i br while i condition i loop br for i from i first i to i last by 1 i br do br i instructions i or dotimes i N br i instructions i or do i i first i 1 i gt i i last i br br i instructions i loop br for i item i in i list i br do br i instructions i or loop br for i item i across i vector i br do br i instructions i or dolist i item list i br i instructions i or mapc i function list i or map i type function sequence i Scheme do i notcondition i i instructions i or let loop if i condition i begin i instructions i loop let loop i instructions i if i condition i loop do i i first i i 1 gt i i last i i instructions i or let loop i i first i if lt i i last i begin i instructions i loop i 1 for each lambda i item i i instructions i i list i ISLISP while i condition instructions i tagbody loop i instructions i if i condition i go loop for i i first i i 1 gt i i last i i instructions i mapc lambda i item i i instructions i i list i Pascal while i condition i do begin br i instructions i br end repeat br i instructions i br until i notcondition i for i i i i first i step 1 to i last i do begin br i instructions i br end a for i item i in i set i do i instructions i Visual Basic Do While i condition i br i instructions i br LooporDo Until i notcondition i br i instructions i br LooporWhile i condition i br i instructions i br Wend Visual Basic NET uses End While instead Do br i instructions i br Loop While i condition i orDo br i instructions i br Loop Until i notcondition i i must be declared beforehand For i i i i first i To i last i Step i 1 br instructions i br Next i For Each i item i In i set i br i instructions i br Next i item i Visual Basic NET For i As i type i i first i To i last i Step i 1 br instructions i br Next i a For Each i item i As i type i In i set i br i instructions i br Next i item i Xojo While i condition i br i instructions i br Wend Do Until i notcondition i br i instructions i br LooporDo br i instructions i br Loop Until i notcondition i Python while i condition i br kbd class keyboard key nowrap Tab kbd i instructions i br else br kbd class keyboard key nowrap Tab kbd i instructions i Python 3 x for i in range i first i i last 1 i br kbd class keyboard key nowrap Tab kbd i instructions i br else br kbd class keyboard key nowrap Tab kbd i instructions i Python 2 x for i in xrange i first i i last 1 i br kbd class keyboard key nowrap Tab kbd i instructions i br else br kbd class keyboard key nowrap Tab kbd i instructions i for i item i in i set i br kbd class keyboard key nowrap Tab kbd i instructions i br else br kbd class keyboard key nowrap Tab kbd i instructions i S Lang while i condition i i instructions i then i optional block i do i instructions i while i condition i then i optional block i for i i first i i lt i last i i i instructions i then i optional block i foreach i item i i set i using i what i i instructions i then i optional block i Fortran DO WHILE i condition i br i instructions i br ENDDO DO br i instructions i br IF i condition i EXIT br ENDDO DO i I i i first i i last i br i instructions i br ENDDO Forth BEGIN i instructions condition i WHILE i instructions i REPEAT BEGIN i instructions condition i UNTIL i limit start i DO i instructions i LOOP OCaml while i condition i do i instructions i done for i i first i to i last i do i instructions i done Array iter fun i item i gt i instructions i i array i orList iter fun i item i gt i instructions i i list i F while i condition i do br kbd class keyboard key nowrap Tab kbd i instructions i for i i first i to i last i do br kbd class keyboard key nowrap Tab kbd i instructions i for i item i in i set i do br kbd class keyboard key nowrap Tab kbd i instructions i orSeq iter fun i item i gt i instructions i i set i Standard ML while i condition i do i instructions i Array app fn i item i gt i instructions i i array i orapp fn i item i gt i instructions i i list i Haskell GHC Control Monad forM i first i i last i i gt do i instructions i Control Monad forM i list i item gt do i instructions i Eiffel from br i setup i br until br i condition i br loop br i instructions i br end CoffeeScript while i condition i br i expression i or i expression i while i condition i orwhile i condition i then i expression i oruntil i condition i br i expression i or i expression i until i condition i oruntil i expression i then i condition i for i i i in i first i i last i br i expression i orfor i i i in i first i i last i then i expression i or i expression i for i i i in i first i i last i for i item i in i set i br i expression i orfor i item i in i set i then i expression i or i expression i for i item i in i set i COBOL PERFORM i procedure 1 i THROUGH i procedure 2 i WITH TEST BEFORE UNTIL i condition i c orPERFORM WITH TEST BEFORE UNTIL i condition i br i expression i br END PERFORM PERFORM i procedure 1 i THROUGH i procedure 2 i WITH TEST AFTER UNTIL i condition i c orPERFORM WITH TEST AFTER UNTIL i condition i br i expression i br END PERFORM PERFORM i procedure 1 i THROUGH i procedure 2 i VARYING i i i FROM i first i BY i increment i UNTIL i i i gt i last i d orPERFORM VARYING i i i FROM i first i BY i increment i UNTIL i i i gt i last i br i expression i br END PERFORM d Rust while i condition i br i expression i br loop br i expression i br if i condition i br break br br for i in i first i i last 1 i br i expression i br orfor i in i first i i last i br i expression i br for i item i in i set i br i expression i br e or i set i into iter for each i item i 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 nbsp as well as the existential quantifier there exists or displaystyle exists nbsp c THRU may be used instead of THROUGH d IS GREATER THAN may be used instead of gt e Type of set expression must implement trait std iter IntoIterator Exceptions edit Further information Exception handling syntax throw handler assertion Ada 1 raise i exception name i with i string expression i begin br i statements i br exception br when i exception list sub 1 sub i gt i statements i br when i exception list sub 2 sub i gt i statements i br i i br when others gt i statements i br end b pragma Assert Check gt i boolean expression i Message gt i string expression i br i function procedure entry i with br Pre gt i boolean expression i br Post gt i boolean expression i br i any type i with Type Invariant gt i boolean expression i APL i string expression i SIGNAL i number expression i Trap i number s expression i br i statements i br Case i number s expression i br i statements i br i i br Else i number s expression i br i statements i br EndTrap i string expression i SIGNAL 98 i condition i C C99 a href Longjmp html class mw redirect title Longjmp longjmp a i state i i exception i switch a href Setjmp html class mw redirect title Setjmp setjmp a i state i case 0 i instructions i break case i exception i i instructions i assert i condition i C throw i exception i try i instructions i catch i exception i i instructions i i i C try i instructions i catch i exception name i i instructions i i i finally i instructions i System Diagnostics Debug Assert i condition i orSystem Diagnostics Trace Assert i condition i Java try i instructions i catch i exception i i instructions i i i finally i instructions i assert i condition i i description i JavaScript try i instructions i catch i exception i i instructions i finally i instructions i D try i instructions i catch i exception i i instructions i i i finally i instructions i assert i condition i PHP try i instructions i catch i exception i i instructions i i i finally i instructions i assert i condition i S Lang try i instructions i catch i exception i i instructions i i i finally i instructions i Windows PowerShell trap i exception i i instructions i i instructions i ortry i instructions i catch i exception i i instructions i i i finally i instructions i Debug Assert i condition i Objective C throw i exception i try i instructions i catch i exception i i instructions i i i finally i instructions i NSAssert i condition i i description i Swift throw i exception i 2 x do try i expression i i instructions i catch i exception i i instructions i i i 2 x assert i condition i i description i Perl die i exception i eval i instructions i if i instructions i Raku try i instructions i CATCH when i exception i i instructions i i i Ruby raise i exception i begin br i instructions i br rescue i exception i br i instructions i br i i br else br i instructions i br ensure br i instructions i br end Smalltalk i exception i raise i instructionBlock i on i exception i do i handlerBlock i assert i conditionBlock i Common Lisp error i exception i or error br i type i br i arguments i or error make condition br i type i br i arguments i handler case br progn i instructions i br i exception instructions i br i i or handler bind br i condition i br lambda br i instructions i br invoke restart i restart args i br i i a assert i condition i or assert i condition i br i place i br i error i or check type i var type i Scheme R6RS raise i exception i guard con i condition instructions i i i i instructions i ISLISP error i error string objects i or signal condition i condition continuable i with handler br i handler form i br Pascal raise i Exception Create i try i Except i on i E exception i do begin i instructions i end end Visual Basic Err Raise i ERRORNUMBER i With New i Try i On Error Resume Next br i OneInstruction br Catch i On Error GoTo 0 Select Case i Number i br Case i SOME ERRORNUMBER i br i instructions i br 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 i condition i Visual Basic NET Throw i exception i orError i errorcode i Try br i instructions i br Catch i name i As i exception i When i condition i br i instructions i br i i br Finally br i instructions i br End Try System Diagnostics Debug Assert i condition i orSystem Diagnostics Trace Assert i condition i Xojo Raise i exception i Try br i instructions i br Catch i exception i br i instructions i br i i br Finally br i instructions i br End Try Python raise i exception i try br kbd class keyboard key nowrap Tab kbd i instructions i br except i exception i br kbd class keyboard key nowrap Tab kbd i instructions i br i i br else br kbd class keyboard key nowrap Tab kbd i instructions i br finally br kbd class keyboard key nowrap Tab kbd i instructions i assert i condition i Fortran Forth i code i THROW i xt i CATCH i code or 0 i OCaml raise i exception i try i expression i with i pattern i gt i expression i assert i condition i F try i expression i with i pattern i gt i expression i ortry i expression i finally i expression i Standard ML raise i exception arg i i expression i handle i pattern i gt i expression i Haskell GHC throw i exception i orthrowError i expression i catch i tryExpression catchExpression i orcatchError i tryExpression catchExpression i assert i condition expression i COBOL RAISE EXCEPTION i exception i USE AFTER EXCEPTION OBJECT i class name i orUSE AFTER EO i class name i orUSE AFTER EXCEPTION CONDITION i exception name i FILE i file name i orUSE AFTER EC i exception name i FILE i file name i Rust No 13 assert i condition i 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 edit exit block break continue label branch goto return value from generator Ada 1 exit i loop name i when i condition i i label i goto i label i ALGOL 68 i value i exit do i statements i skip exit i label statements i od label go to i label i br goto i label br label i yield value Callback 14 APL Leave Continue i label i i label i or GoTo i label i C C99 break continue i label i goto i label i Objective C C STL D C yield return i value i Java break i label i continue i label i JavaScript yield i value i PHP break i levels i continue i levels i goto i label i yield i key gt value i Perl last i label i next i label i Raku Go break i label i continue i label i goto i label i Swift break i label i continue i label i Bash shell break i levels i continue i levels i Common Lisp return or return from i block i or loop finish tagbody i tag i br i i br i tag i br i i go i tag i Scheme ISLISP return from i block i tagbody i tag i br i i br i tag i br i i go i tag i Pascal ISO i label i a goto i label i Pascal FPC break continue Visual Basic Exit i block i Alternatively for methods Return i label i GoTo i label i Xojo Continue i block i Visual Basic NET Yield i value i Python break continue yield i value i RPG IV LEAVE ITER S Lang break continue Fortran EXIT CYCLE label b GOTO i label i Ruby break next Windows PowerShell break i label i continue OCaml F Standard ML Haskell GHC COBOL EXIT PERFORM or EXIT PARAGRAPH or EXIT SECTION or EXIT EXIT PERFORM CYCLE i label i SECTION GO TO i label i a Pascal has declaration blocks See functions b label must be a number between 1 and 99999 Functions editSee reflective programming for calling and declaring functions by strings calling a function basic void function value returning function required main function Ada 1 i foo parameters i procedure i foo parameters i is begin i statements i end i foo i function i foo parameters i return i type i is begin i statements i end i foo i ALGOL 68 i foo parameters i proc i foo i i parameters i a href Void type html title Void type void a i instructions i proc i foo i i parameters i rettype i instructions retvalue i APL i parameters i foo i parameters i i foo i i statements i i foo i i statements i C C99 i foo i i parameters i a href Void type html title Void type void a i foo i i parameters i i instructions i i type i i foo i i parameters i i instructions i return i value i i global declarations i br int main int argc char argv br i instructions i br Objective C C STL Java public static void main String args i instructions i orpublic static void main String a href Variadic function html title Variadic function a args i instructions i D int main char args i instructions i orint main string args i instructions i orvoid main char args i instructions i orvoid main string args i instructions i C Same as above alternatively if only one statement a href Void type html title Void type void a foo i parameters i gt i statement i Same as above alternatively if simple enough to be an expression a href Void type html title Void type void a foo i parameters i gt i expression i static void Main string args method bodyMay instead return int starting with C 7 1 May return Task or Task lt int gt and if so may be async JavaScript function foo i parameters i i instructions i orvar foo function i parameters i i instructions i orvar foo new Function i parameter i i i i last parameter i i instructions i function foo i parameters i i instructions i return i value i Go func foo i parameters i i instructions i func foo i parameters i i type i i instructions i return i value i func main i instructions i Swift func foo i parameters i i instructions i func foo i parameters i gt i type i i instructions i return i value i Common Lisp foo i parameters i a href Defun html class mw redirect title Defun defun a foo i parameters i br i instructions i or setf symbol function i symbol i br i function i a href Defun html class mw redirect title Defun defun a foo i parameters i br i br value i Scheme define foo i parameters i i instructions i or define foo a href Anonymous function html title Anonymous function lambda a i parameters i i instructions i define foo i parameters i i instructions return value i or define foo a href Anonymous function html title Anonymous function lambda a i parameters i i instructions return value i ISLISP a href Defun html class mw redirect title Defun defun a foo i parameters i br i instructions i a href Defun html class mw redirect title Defun defun a foo i parameters i br i br value i Pascal foo i parameters i procedure foo i parameters i forward sup class plainlinks nourlexpansion citation id ref forward declaration a href endnote forward declaration a a sup br label br i label declarations i br const br i constant declarations i br type br i type declarations i br var br i variable declarations br local function declarations i br begin br i instructions i br end function foo i parameters i i type i forward sup class plainlinks nourlexpansion citation id ref forward declaration a href endnote forward declaration a a sup br label br i label declarations i br const br i constant declarations i br type br i type declarations i br var br i variable declarations br local function declarations i br begin br i instructions i br foo i value i br end program i name i br label br i label declarations i br const br i constant declarations i br type br i type declarations i br var br i variable declarations br function declarations i br begin br i instructions i br end Visual Basic Foo i parameters i Sub Foo i parameters i br i instructions i br End Sub Function Foo i parameters i As i type i br i instructions i br Foo i value i br End Function Sub Main br i instructions i br End Sub Visual Basic NET Same as above alternatively Function Foo i parameters i As i type i br i instructions i br Return i value i br End 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 br i instructions i br End SuborFunction Main ByVal args As String As Integer br i instructions i br End Function Xojo Python foo i parameters i def foo i parameters i br kbd class keyboard key nowrap Tab kbd i instructions i def foo i parameters i br kbd class keyboard key nowrap Tab kbd i instructions i br kbd class keyboard key nowrap Tab kbd return i value i S Lang foo i parameters qualifiers i define foo i parameters i i instructions i define foo i parameters i i instructions i return i value i public define slsh main i instructions i Fortran foo i arguments i br CALL sub foo i arguments i c SUBROUTINE sub foo i arguments i br i instructions br i END SUBROUTINE c i type i FUNCTION foo i arguments i br i instructions i br i i br i foo i i value i br END FUNCTION c PROGRAM i main i br i instructions i br END PROGRAM Forth i parameters i FOO FOO stack effect comment i before i br i instructions i br FOO stack effect comment i before i i after i br i instructions i br PHP foo i parameters i function foo i parameters i i instructions i function foo i parameters i i instructions i return i value i Perl foo i parameters i or amp foo i parameters i sub foo my i parameters i i instructions i sub foo my i parameters i i instructions i return i value i Raku foo i parameters i or amp foo i parameters i multi sub foo i parameters i i instructions i our i type i multi sub foo i parameters i i instructions i return i value i Ruby foo i parameters i def foo i parameters i br i instructions i br end def foo i parameters i br i instructions i br return i value i br end Rust foo i parameters i fn foo i parameters i i instructions i fn foo i parameters i gt i type i i instructions i fn main i instructions i Scala i foo i i parameters i def i foo i i parameters i Unit i instructions i def i foo i i parameters i i type i i instructions i return i value i def main args Array String i instructions i Windows PowerShell foo i parameters i function i foo i i instructions i orfunction i foo i param i parameters i i instructions i function i foo i i parameters i i instructions i return i value i orfunction foo param i parameters i i instructions i return i value i Bash shell foo i parameters i function foo br i instructions i br orfoo br i instructions i br function foo br i instructions i br return i exit code i br orfoo br i instructions i br return i exit code i br parameters i n i 1 2 3 all parameters the number of parameters 0 this function name OCaml foo i parameters i let rec foo i parameters i i instructions i let rec foo i parameters i i instructions return value i F lt EntryPoint gt let main args i instructions i Standard ML fun foo i parameters i i instructions i fun foo i parameters i i instructions return value i Haskell foo i parameters i do br kbd class keyboard key nowrap Tab kbd i instructions i foo i parameters i i return value i orfoo i parameters i do br kbd class keyboard key nowrap Tab kbd i instructions i br kbd class keyboard key nowrap Tab kbd return i value i main IO br main do i instructions i Eiffel foo i parameters i foo i parameters i br require br i preconditions i br do br i instructions i br ensure br i postconditions i br end foo i parameters i i type i br require br i preconditions i br do br i instructions i br Result i value i br ensure br i postconditions i br end b CoffeeScript foo foo gt foo gt i value i foo i parameters i foo gt foo i parameters i gt i value i COBOL CALL i foo i USING i parameters br exception handling br i END CALL i i d IDENTIFICATION DIVISION br PROGRAM ID i foo i i br other divisions br i PROCEDURE DIVISION i i USING i parameters i i br instructions i IDENTIFICATION DIVISION br PROGRAM ID FUNCTION ID i foo i br i other divisions i br DATA DIVISION br i other sections i br LINKAGE SECTION br i parameter definitions i br i variable to return definition i br i other sections i br PROCEDURE DIVISION USING i parameters i RETURNING i variable to return i br i instructions i FUNCTION i foo parameters i 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 editWhere 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 i string expression i Long Integer Value i string expression i Float Value i string expression i Integer Image i integer expression i Float Image i float expression i ALGOL 68 with general and then specific formats With prior declarations and association of string i buf 12345678 9012e34 i file i proxy associate proxy buf i 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 APL i string expression i i string expression i i string expression i i integer expression i i float expression i C C99 i integer i a href Atoi html class mw redirect title Atoi atoi a i string i i long i a href Atol programming html class mw redirect title Atol programming atol a i string i i float i a href Atof html class mw redirect title Atof atof a i string i a href Sprintf html class mw redirect title Sprintf sprintf a i string i i i integer i a href Sprintf html class mw redirect title Sprintf sprintf a i string i f i float i Objective C i integer i i string i intValue i long i i string i longLongValue i float i i string i doubleValue i string i NSString stringWithFormat wbr wbr i i integer i i string i NSString stringWithFormat wbr wbr f i float i C STL std istringstream i string i gt gt i number i std ostringstream i o i i o i lt lt i number i i string i i o i str C 11 i integer i i std i stoi i string i i long i i std i stol i string i i float i i std i stof i string double i i std i stod i string i i string i i std i to string i number i C i integer i int Parse wbr wbr i string i i long i long Parse wbr wbr i string i i float i float Parse wbr wbr i string i i double i double Parse wbr wbr i string i i string i i number i wbr wbr ToString D i integer i std conv to int wbr wbr i string i i long i std conv to long wbr wbr i string i i float i std conv to float wbr wbr i string i i double i std conv to double wbr wbr i string i i string i std conv to string wbr wbr i number i Java i integer i Integer parseInt wbr wbr i string i i long i Long parseLong wbr wbr i string i i float i Float parseFloat wbr wbr i string i i double i Double parseDouble wbr wbr i string i i string i Integer toString wbr wbr i integer i i string i String valueOf wbr wbr i integer i i string i Float toString wbr wbr i float i i string i Double toString wbr wbr i double i JavaScript a i integer i parseInt i string i i float i parseFloat i string i i float i new Number i string i i float i Number i string i i float i i string i i string i i number i toString i string i String i number i i string i i number i i string i i number i Go i integer i i error i strconv Atoi i string i br i integer i i error i strconv ParseInt wbr wbr i string i 10 0 i long i i error i strconv ParseInt wbr wbr i string i 10 64 i float i i error i strconv ParseFloat wbr wbr i string i 64 i string i strconv Itoa i integer i i string i strconv FormatInt wbr wbr i integer i 10 i string i fmt Sprint i integer i i string i strconv FormatFloat wbr wbr i float i i string i fmt Sprint wbr wbr i float i Rust d i string i parse lt i32 gt i32 from str i string i i string i parse lt i64 gt i64 from str i string i i string i parse lt f64 gt f64 from str i string i i integer i to string i float i to string Common Lisp setf i integer i parse integer i string i setf i float i read from string i string i setf i string i princ to string i number i Scheme define i number i string gt number i string i define i string i number gt string i number i ISLISP setf i integer i convert i string i lt integer gt setf i float i convert i string i lt float gt setf i string i convert i number i lt string gt Pascal i integer i StrToInt i string i i float i StrToFloat i string i i string i IntToStr i integer i i string i FloatToStr i float i Visual Basic i integer i CInt i string i i long i CLng i string i i float i CSng i string i br i double i CDbl i string i i string i CStr i number i Visual Basic NET can use both VB syntax above and NET methods shown right i integer i Integer Parse wbr wbr i string i i long i Long Parse wbr wbr i string i i float i Single Parse wbr wbr i string i i double i Double Parse wbr wbr i string i i string i i number i wbr wbr ToString Xojo i integer i Val i string i i long i Val i string i i double i Val i string i i double i CDbl i string i i string i CStr i number i or i string i Str i number i Python i integer i int i string i i long i long i string i i float i float i string i i string i str i number i S Lang i integer i a href Atoi html class mw redirect title Atoi atoi a i string i i long i a href Atol programming html class mw redirect title Atol programming atol a i string i i float i a href Atof html class mw redirect title Atof atof a i string i i string i string i number i Fortran READ i string i i format i i number i WRITE i string i i format i i number i PHP i integer i intval i string i or i integer i int i string i i float i floatval i string i i float i float i string i i string i i number i or i string i strval i number i or i string i string i number i Perl b i number i 0 i string i i string i i number i Raku i number i i string i i string i i number i Ruby i integer i i string i to ior i integer i Integer i string i i float i i string i to f i float i Float i string i i string i i number i to s Scala i integer i i string i toInt i long i i string i toLong i float i i string i toFloat i double i i string i toDouble i string i i number i toString Smalltalk i integer Integer i readFrom i string i i float Float i readFrom i string i i string number i asString Windows PowerShell i integer i int i string i i long i long i string i i float i float i string i i string i string i number i or i string i i number i or i string i i number i ToString OCaml let i integer i int wbr wbr of string i string i let i float i float wbr wbr of string i string i let i string i string wbr wbr of int i integer i let i string i string wbr wbr of float i float i F let i integer i int i string i let i integer i int64 i string i let i float i float i string i let i string i string i number i Standard ML val i integer i Int wbr wbr fromString i string i val i float i Real wbr wbr fromString i string i val i string i Int wbr wbr toString i integer i val i string i Real wbr wbr toString i float i Haskell GHC i number i read i string i i string i show i number i COBOL MOVE FUNCTION NUMVAL i string i sup class plainlinks nourlexpansion citation id ref COBOL s NUMVAL alternatives a href endnote COBOL s NUMVAL alternatives c a sup TO i number i MOVE i number i TO i numeric edited i a JavaScript only uses floating point numbers so there are some technicalities 7 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 lt gt on str parse can be omitted if the type can be inferred from context Standard stream I O editread from write to stdin stdout stderr Ada 1 Get i x i Put i x i Put Standard Error i x i ALGOL 68 readf i format i i x i orgetf stand in i format i i x i a href Printf html title Printf printf a i format i i x i orputf stand out i format i i x i putf stand error i format i i x i a APL i x i i x i i x i C C99 a href Scanf html title Scanf scanf a i format i amp i x i or a href Fscanf html class mw redirect title Fscanf fscanf a stdin i format i amp i x i b a href Printf html title Printf printf a i format i i x i or a href Fprintf html class mw redirect title Fprintf fprintf a stdout i format i i x i c a href Fprintf html class mw redirect title Fprintf fprintf a stderr i format i i x i d Objective C span class n data span span class w span span class o span span class w span span class p span span class bp NSFileHandle span span class w span span class n fileHandleWithStandardInput span span class p span span class w span span class n readDataToEndOfFile span span class p span span class p span span class bp NSFileHandle span span class w span span class n fileHandleWithStandardOutput span span class p span span class w span span class n writeData span span class o span span class n data span span class p span span class p span span class bp NSFileHandle span span class w span span class n fileHandleWithStandardError span span class p span span class w span span class n writeData span span class o span span class n data span span class p span C a href Iostream html class mw redirect title Iostream std cin a gt gt i x i or std getline std cin i str i a href Iostream html class mw redirect title Iostream std cout a lt lt i x i a href Iostream html class mw redirect title Iostream std cerr a lt lt i x i or a href Iostream html class mw redirect title Iostream std clog a lt lt i x i C i x i Console Read or i x i Console ReadLine Console Write i format i i x i orConsole WriteLine i format i i x i Console Error wbr wbr Write i format i i x i orConsole Error wbr wbr WriteLine i format i i x i D i x i std stdio readln std stdio write i x i orstd stdio writeln i x i orstd stdio writef i format i i x i orstd stdio writefln i format i i x i stderr write i x i orstderr writeln i x i orstd stdio wbr wbr writef stderr i format i i x i orstd stdio wbr wbr writefln stderr i format i i x i Java x System in read orx new Scanner System in nextInt orx new Scanner System in nextLine System out print i x i orSystem out a href Printf html title Printf printf a i format i i x i orSystem out println i x i System err print i x i orSystem err a href Printf html title Printf printf a i format i i x i orSystem err println i x i Go fmt Scan amp i x i orfmt a href Scanf html title Scanf Scanf a i format i amp i x i orx bufio NewReader os Stdin ReadString n fmt Println i x i orfmt a href Printf html title Printf Printf a i format i i x i fmt Fprintln os Stderr x orfmt a href Fprintf html class mw redirect title Fprintf Fprintf a os Stderr i format i i x i Swift i x i readLine 2 x print i x i 2 x println i x i 1 x JavaScriptWeb Browser implementation document write i x i JavaScriptActive Server Pages Response Write i x i JavaScriptWindows Script Host i x i WScript StdIn Read i chars i or i x i WScript StdIn ReadLine WScript Echo i x i orWScript StdOut Write i x i orWScript StdOut WriteLine i x i WScript StdErr Write i x i orWScript StdErr WriteLine i x i Common Lisp setf x read line princ i x i or format t i format x i princ x error output or code class mw highlight mw highlight lang lisp mw content ltr id style background none border none color inherit padding 0px 0px dir ltr span class p span span class nb format span span class w span span class vg error output span format x code Scheme R6RS define x read line display i x i or code class mw highlight mw highlight lang scheme mw content ltr id style background none border none color inherit padding 0px 0px dir ltr span class p span span class nb format span span class w span span class no t span format x code display x current error port or code class mw highlight mw highlight lang scheme mw content ltr id style background none border none color inherit padding 0px 0px dir ltr span class p span span class nb format span span class w span span class p span span class nb current error port span span class p span format x code ISLISP setf x read line code class mw highlight mw highlight lang lisp mw content ltr id style background none border none color inherit padding 0px 0px dir ltr span class p span span class nb format span span class w span span class p span span class nv standard output span span class p span format x code code class mw highlight mw highlight lang lisp mw content ltr id style background none border none color inherit padding 0px 0px dir ltr span class p span span class nb format span span class w span span class p span span class nv error output span span class p span format x code Pascal read i x i orreadln i x i write i x i orwriteln i x i write stderr i x i orwriteln stderr i x i Visual Basic Input i prompt i i x i Print i x i or i x i Visual Basic NET i x i Console Read or i x i Console ReadLine Console Write i format i i x i orConsole WriteLine i format i i x i Console Error wbr wbr Write i format i i x i orConsole Error wbr wbr WriteLine i format i i x i Xojo i x i StandardInputStream Read or i x i StandardInputStreame ReadLine StandardOutputStream Write i x i orStandardOutputStream WriteLine i x i StdErr Write i x i orStdErr WriteLine i x i Python 2 x i x i raw input i prompt i print i x i orsys stdout write i x i code class mw highlight mw highlight lang python2 mw content ltr id style background none border none color inherit padding 0px 0px dir ltr span class k print span span class o gt gt span span class n sys span span class o span span class n stderr span span class p span x code orsys stderr write i x i Python 3 x i x i input i prompt i print i x i end print i x i end file sys stderr S Lang a href Fgets html class mw redirect title Fgets fgets a amp i x i stdin a href Fputs html class mw redirect title Fputs fputs a i x i stdout a href Fputs html class mw redirect title Fputs fputs a i x i stderr Fortran READ i format i i variable names i orREAD INPUT UNIT i format i i variable names i e WRITE i format i i expressions i orWRITE OUTPUT UNIT i format i i expressions i e WRITE ERROR UNIT i format i i expressions i e Forth i buffer length i ACCEPT i chars read i br KEY i char i i buffer length i TYPE br i char i EMIT PHP i x i a href Fgets html class mw redirect title Fgets fgets a STDIN or i x i a href Fscanf html class mw redirect title Fscanf fscanf a STDIN i format i print i x i or a href Echo command html title Echo command echo a i x i or a href Printf html title Printf printf a i format i i x i a href Fprintf html class mw redirect title Fprintf fprintf a STDERR i format i i x i Perl i x i lt gt or i x i lt STDIN gt print i x i or a href Printf html title Printf printf a i format i i x i print STDERR i x i or a href Printf html title Printf printf a STDERR i format i i x i Raku x IN get i x i printor i x i say i x i noteor ERR print x or ERR say x Ruby i x i gets puts i x i or a href Printf html title Printf printf a i format i i x i stderr puts x or stderr a href Printf html title Printf printf a i format i i x i Windows PowerShell i x i Read Host Prompt i text i or x Console Read or x Console ReadLine i x i orWrite Output i x i orecho i x i Write Error i x i OCaml let i x i read int orlet i str i read line orScanf a href Scanf html title Scanf scanf a i format i fun i x i gt i i print int i x i orprint endline i str i orPrintf a href Printf html title Printf printf a i format x i prerr int i x i orprerr endline i str i orPrintf a href Fprintf html class mw redirect title Fprintf eprintf a i format x i F let x System Console ReadLine a href Printf html title Printf printf a i format x i or a href Printf html title Printf printfn a i format x i a href Fprintf html class mw redirect title Fprintf eprintf a i format x i or a href Fprintf html class mw redirect title Fprintf eprintfn a i format x i Standard ML val str TextIO inputLIne TextIO stdIn print i str i code class mw highlight mw highlight lang sml mw content ltr id style background none border none color inherit padding 0px 0px dir ltr span class nn TextIO span span class p span span class n output span span class p span span class nn TextIO span span class p span span class n stdErr span span class p span str code Haskell GHC i x i lt readLnor i str i lt getLine print i x i orputStrLn i str i hPrint stderr i x i orhPutStrLn stderr i str i COBOL ACCEPT i x i DISPLAY i x i a ALGOL 68 additionally as the unformatted transput routines read write get and put b a href Gets html class mw redirect title Gets gets a x and a href Fgets html class mw redirect title Fgets fgets a x i length i stdin read unformatted text from stdin Use of gets is not recommended c a href Puts C html class mw redirect title Puts C puts a x and a href Fputs html class mw redirect title Fputs fputs a 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 15 Reading command line arguments editArgument values Argument counts Program name Script name Ada 1 Argument i n i Argument Count Command Name C C99 argv i n i argc first argument Objective C C C args i n i args Length Assembly GetEntryAssembly wbr wbr Location Java args length D first argument JavaScriptWindows Script Host implementation WScript Arguments i n i WScript Arguments length WScript ScriptNameorWScript ScriptFullName Go os Args i n i len os Args first argument Rust a std env args nth i n i std env args os nth i n i std env args count std env args os count std env args next std env args os next Swift Process arguments i n i orProcess unsafeArgv i n i Process arguments count orProcess argc first argument Common Lisp Scheme R6RS list ref command line n length command line first argument ISLISP Pascal ParamStr i n i ParamCount first argument Visual Basic Command b App Path Visual Basic NET CmdArgs i n i CmdArgs Length Assembly GetEntryAssembly Location Xojo System CommandLine string parsing Application ExecutableFile Name Python sys argv i n i len sys argv first argument S Lang argv i n i argc first argument Fortran DO i i i i 1 i i argc i br CALL GET COMMAND ARGUMENT i i i i argv i i br ENDDO i argc i COMMAND ARGUMENT COUNT CALL GET COMMAND ARGUMENT i 0 i i progname i PHP argv i n i argc first argument Bash shell i n i 1 2 3 i i all arguments 0 Perl ARGV i n i scalar ARGV 0 Raku ARGS i n i ARGS elems PROGRAM NAME Ruby ARGV i n i ARGV size 0 Windows PowerShell args i n i args Length MyInvocation MyCommand wbr wbr Name OCaml Sys argv i n i Array length Sys argv first argument F args i n i args Length Assembly GetEntryAssembly wbr wbr Location Standard ML span class nn List span span class p span span class n nth span span class p span span class nn CommandLine span span class p span span class n arguments span span class p span span class n n span span class p span span class n length span span class p span span class nn CommandLine span span class p span span class n arguments span span class p span span class nn CommandLine span span class p span span class n name span span class p span Haskell GHC span class kr do span span class w span span class p span span class w span span class n args span span class w span span class ow lt span span class w span span class kt System span span class o span span class n getArgs span span class p span span class w span span class n return span span class w span span class n length span span class w span span class n args span span class w span span class o span span class w span span class n n span span class kr do span span class w span span class p span span class w span span class n args span span class w span span class ow lt span span class w span span class kt System span span class o span span class n getArgs span span class p span span class w span span class n return span span class w span span class n length span span class w span span class n args span 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 i string i 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 editShell 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 a href System C standard library html class mw redirect title System C standard library system a i command i a href Exec operating system html class mw redirect title Exec operating system execl a i path i i args i or a href Exec operating system html class mw redirect title Exec operating system execv a i path i i arglist i C Objective C NSTask launchedTaskWithLaunchPath NSString path arguments NSArray arguments C System Diagnostics wbr wbr Process Start i path i i argstring i F Go exec Run i path i i argv i i envv i i dir i exec DevNull exec DevNull exec DevNull os Exec i path i i argv i i envv i Visual Basic Interaction Shell i command i i WindowStyle i i isWaitOnReturn i Visual Basic NET Microsoft VisualBasic wbr wbr Interaction Shell i command i i WindowStyle i i isWaitOnReturn i System Diagnostics wbr wbr Process Start i path i i argstring i Xojo Shell Execute i command i i Parameters i FolderItem Launch i parameters i i activate i D std process system i command i std process execv i path i i arglist i Java Runtime exec i command i ornew ProcessBuilder command start JavaScriptWindows Script Host implementation code class mw highlight mw highlight lang js mw content ltr id style background none border none color inherit padding 0px 0px dir ltr span class nx WScript span span class p span span class nx CreateObject span span class w span span class p span span class s2 WScript Shell span span class p span span class nx Run span span class p span command WindowStyle isWaitOnReturn code WshShell Exec command Common Lisp uiop run program i command i Scheme system i command i ISLISP Pascal system i command i OCaml Sys command i command i Unix open process full i command env stdout stdin stderr i Unix create process i prog args new stdin new stdout new stderr i Unix execv i prog args i orUnix execve i prog args env i Standard ML OS Process system i command i Unix execute i path i i args i Posix Process exec i path i i args i Haskell GHC System system i command i System Process wbr wbr runProcess i path args i Posix Process wbr wbr executeFile i path i True i args i Perl system i command i or i output i i command i or i output i qx i command i exec i path i i args i Ruby system i command i or i output i i command i exec i path i i args i PHP system i command i or i output i i command i orexec i command i orpassthru i command i Python os system i command i orsubprocess Popen i command i subprocess call i program arg1 arg2 i os execv i path i i args i S Lang system i command i Fortran CALL EXECUTE COMMAND LINE i COMMAND i i WAIT i i EXITSTAT i i CMDSTAT i i CMDMSG i a Windows PowerShell Diagnostics Process Start command Invoke Item i program arg1 arg2 i Bash shell i output i i command i or i output i i command i program arg1 arg2 a Fortran 2008 or newer 17 References edit a b c d e f g h i j k l m n o p 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 Common Lisp HyperSpec TM lispworks com Retrieved 30 January 2017 www islisp info Specification islisp info Archived from the original on 22 January 2016 Retrieved 30 January 2017 a b selected int kind in Fortran Wiki fortranwiki org Retrieved 30 January 2017 Erlang Types and Function Specifications erlang org Retrieved 30 January 2017 Erlang Advanced erlang org Retrieved 30 January 2017 a b 8 5 The Number Type a b selected real kind in Fortran Wiki fortranwiki org Retrieved 30 January 2017 The GNU C Library Complex Numbers gnu org Retrieved 30 January 2017 Grammar vb Visual Basic Language Specification 2016 06 17 Archived from the original on 2019 08 29 Retrieved 2019 08 29 for of mozilla org Retrieved 30 January 2017 Try Catch for VB google com Archived from the original on 16 April 2016 Retrieved 30 January 2017 Klabnik Steve Nichols Carol Error Handling The Rust Programming Language Prime decomposition Rosetta Code rosettacode org Retrieved 30 January 2017 iso fortran env in Fortran Wiki fortranwiki org Retrieved 30 January 2017 Execute a system command Rosetta Code rosettacode org Retrieved 30 January 2017 EXECUTE COMMAND LINE The GNU Fortran Compiler gnu org Retrieved 30 January 2017 Retrieved from https en wikipedia org w index php title Comparison of programming languages basic instructions amp oldid 1213663234 Variable and constant declarations, wikipedia, wiki, book, books, library,

article

, read, download, free, free download, mp3, video, mp4, 3gp, jpg, jpeg, gif, png, picture, music, song, movie, book, game, games.