From Surf Wiki (app.surf) — the open knowledge base
Comparison of programming languages (basic instructions)
None
None
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. TOC
Conventions of this article
Generally, var, var, or 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. 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
[[Integer (computer science)|Integer]]s
| 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 | or | or | or | `Integer` | or | ||||||||||||||||
| ALGOL 68 (variable-width) | `short short int` | rowspan=2 | `short int` | rowspan=2 | `int` | rowspan=2 | `long int` | rowspan=2 | `int` | `long long int` | |||||||||||
| `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` | `size_t` | rowspan=5 | ||||||||||
| C++ (C++11 fixed-width) | |||||||||||||||||||||
| C (C99 variable-width) | `signed char` | `unsigned char`, `byte` (C++17) | `short` | `unsigned short` | `long` | `unsigned long` | `long long` | `unsigned long long` | `int` | `unsigned int` | |||||||||||
| 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` | `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` | ||||||||||||
| url=http://www.lispworks.com/documentation/HyperSpec/Front/index.htm | title=Common Lisp HyperSpec (TM) | work=lispworks.com | access-date=30 January 2017}} | `(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 | |||||||||||||||||||||
| url=http://www.islisp.info/specification.html | title=www.islisp.info: Specification | work=islisp.info | access-date=30 January 2017 | archive-url=https://web.archive.org/web/20160122121427/http://islisp.info/specification.html | archive-date=22 January 2016 | url-status=dead}} | `bignum` | ||||||||||||||
| Pascal (FPC) | `shortint` | `byte` | `smallint` | `word` | `longint` | `longword` | `int64` | `qword` | `integer` | `cardinal` | |||||||||||
| Visual Basic | `Byte` | `Integer` | `Long` | colspan=2 | rowspan=2 colspan=2 | rowspan=1 | |||||||||||||||
| Visual Basic .NET | `SByte` | `Short` | `UShort` | `Integer` | `UInteger` | `Long` | `ULong` | `System.Numerics.BigInteger` | |||||||||||||
| (.NET 4.0) | |||||||||||||||||||||
| FreeBasic | `Byte` or `Integer` | `UByte` or `UInteger` | `Short` or `Integer` | `UShort` or `UInteger` | `Long` or `Integer` | `ULong` or `UInteger` | `LongInt` or `Integer` | `ULongInt` or `UInteger` | `Integer` | `UInteger` | |||||||||||
| Python 2.x | colspan=2 | colspan=2 | colspan=2 | colspan=2 | `int` | `long` | |||||||||||||||
| Python 3.x | colspan=2 | colspan=2 | colspan=2 | colspan=2 | colspan=2 | `int` | |||||||||||||||
| S-Lang | colspan=2 | colspan=2 | colspan=2 | colspan=2 | colspan=2 | ||||||||||||||||
| Fortran | |||||||||||||||||||||
| PHP | colspan=2 | colspan=2 | `int` | `int` | colspan=2 | ||||||||||||||||
| Perl 5 | scalars | [d]}} | scalars | [d]}} | scalars | [d]}} | scalars | [d]}} | scalars | [d]}} | `Math::BigInt` | ||||||||||
| Raku | `int8` | `uint8` | `int16` | `uint16` | `int32` | `uint32` | `int64` | `uint64` | `Int` | colspan=2 | |||||||||||
| Ruby | colspan=2 | colspan=2 | colspan=2 | colspan=2 | `Fixnum` | `Bignum` | |||||||||||||||
| Erlang | colspan=2 | colspan=2 | colspan=2 | colspan=2 | `integer()` | `integer()` | |||||||||||||||
| Scala | `Byte` | `Short` | `Char` | `Int` | `Long` | `scala.math.BigInt` | |||||||||||||||
| Seed7 | `integer` | `bigInteger` | |||||||||||||||||||
| Smalltalk | colspan=2 | colspan=2 | colspan=2 | colspan=2 | `SmallInteger` | `LargeInteger` | |||||||||||||||
| Windows PowerShell | colspan=2 | colspan=2 | colspan=2 | colspan=2 | colspan=2 | ||||||||||||||||
| OCaml | colspan=2 | colspan=2 | `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` | colspan=2 | `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 | `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 | colspan=2 | colspan=2 | colspan=2 | colspan=2 | colspan=2 | `Integer` | |||||||||||||||
| Wolfram Language | colspan=2 | colspan=2 | colspan=2 | colspan=2 | colspan=2 | `Integer` |
- The standard constants
int shortsandint lengthscan be used to determine how manyshorts andlongs can be usefully prefixed toshort intandlong int. The actual sizes ofshort int,int, andlong intare available as the constantsshort max int,max int, andlong max intetc. - Commonly used for characters.
- 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, andlong longtypes are required to be at least 16, 32, and 64 bits wide, respectively, but can be more. Theinttype is required to be at least as wide asshortand at most as wide aslong, and is typically the width of the word size on the processor of the machine (i.e. on a 32-bit machine it is often 32 bits wide; on 64-bit machines it is sometimes 64 bits wide). C99 and C++11 also define the[u]intN_texact-width types in the stdint.h header. See C syntax#Integral types for more information. In addition the typessize_tandptrdiff_tare defined in relation to the address size to hold unsigned and signed integers sufficiently large to handle array indices and the difference between pointers. - Perl 5 does not have distinct types. Integers, floating point numbers, strings, etc. are all considered "scalars".
- PHP has two arbitrary-precision libraries. The BCMath library just uses strings as datatype. The GMP library uses an internal "resource" type.
- The value of
nis provided by theSELECTED_INT_KINDintrinsic function. - ALGOL 68G's runtime option
--precision "number"can set precision forlong long ints to the required "number" significant digits. The standard constantslong long int widthandlong long max intcan be used to determine actual precision. - 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. - 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 () and one supporting arbitrary sized integers (). Arithmetic operations support polymorphic arguments and return the result in the most appropriate compact representation.
- 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 () and Natural ().
Short_Short_Integer(8 bits),Short_Integer(16 bits) andLong_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. - Ada modulo types implement modulo arithmetic in all operations, i.e. no range violations are possible. Modulos are not restricted to powers of two.
- Commonly used for characters like Java's char.
intin PHP has the same width aslongtype in C has on that system.- Erlang is dynamically typed. The type identifiers are usually used to specify types of record fields and the argument and return types of functions.
- When it exceeds one word.
[[Floating point]]
| Single precision | Double precision | Other precision | Processor dependent |
|---|---|---|---|
| Ada | `Float` | `Long_Float` | |
| ALGOL 68 | `real` | `long real` | `short real`, `long long real`, etc. |
| C | `float` | `double` | `long double` |
| C++ (STL) | |||
| Objective-C (Cocoa) | `CGFloat` | ||
| C# | `float` | rowspan=3 | |
| Java | |||
| Go | `float32` | `float64` | |
| Rust | `f32` | `f64` | `f16, f128` |
| Swift | `Float` or `Float32` | `Double` or `Float64` | `Float80` |
| D | `float` | `double` | |
| Common Lisp | `single-float` | `double-float` | `float, short-float, long-float` |
| Scheme | |||
| ISLISP | |||
| Pascal (FPC) | `single` | `double` | |
| Visual Basic | `Single` | `Double` | rowspan=3 |
| Visual Basic .NET | |||
| Xojo | |||
| Python | rowspan=2 | `float` | |
| JavaScript | `Number` | ||
| S-Lang | |||
| Fortran | `REAL(KIND = n)` | ||
| PHP | `float` | ||
| Perl | |||
| Raku | `num32` | `num64` | |
| Ruby | `Float` | rowspan=4 | |
| Scala | `Float` | `Double` | |
| Seed7 | `float` | ||
| Smalltalk | `Float` | `Double` | |
| Windows PowerShell | |||
| OCaml | `float` | rowspan=3 | |
| F# | `float32` | ||
| Standard ML | `real` | ||
| Haskell (GHC) | `Float` | `Double` | |
| Eiffel | `REAL_32` | `REAL_64` | |
| COBOL | `FLOAT-BINARY-7` | `FLOAT-BINARY-34` | `FLOAT-SHORT`, `FLOAT-LONG`, `FLOAT-EXTENDED` |
| Mathematica |
- The standard constants
real shortsandreal lengthscan be used to determine how manyshorts andlongs can be usefully prefixed toshort realandlong real. The actual sizes ofshort real,real, andlong realare available as the constantsshort max real,max realandlong max realetc. With the constantsshort small real,small realandlong small realavailable for each type's machine epsilon. - declarations of single precision often are not honored
- The value of
nis provided by theSELECTED_REAL_KINDintrinsic function. - ALGOL 68G's runtime option
--precision "number"can set precision forlong long reals to the required "number" significant digits. The standard constantslong long real widthandlong long max realcan be used to determine actual precision. - These IEEE floating-point types will be introduced in the next COBOL standard.
- Same size as
doubleon many implementations. - Swift supports 80-bit extended precision floating point type, equivalent to
long doublein C languages.
[[Complex number]]s
| Integer | Single precision | Double precision | Half and Quadruple precision etc. |
|---|---|---|---|
| Ada | `Complex` | `Complex` | |
| ALGOL 68 | `compl` | `long compl` etc. | |
| C (C99) | `float complex` | `double complex` | |
| C++ (STL) | . See C++ standard section 26.2 paragraph 2 -- | `std::complex` | `std::complex` |
| 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) |
| Scheme | |||
| Pascal | |||
| Visual Basic | |||
| Visual Basic .NET | `System.Numerics.Complex` | ||
| (.NET 4.0) | |||
| Perl | `Math::Complex` | ||
| Raku | `complex64` | `complex128` | |
| Python | `complex` | ||
| JavaScript | |||
| S-Lang | |||
| Fortran | `COMPLEX(KIND = n)` | ||
| 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` |
- The value of
nis provided by theSELECTED_REAL_KINDintrinsic function. - Generic type which can be instantiated with any base floating point type.
Other variable types
| Text | Boolean | Enumeration | Object/Universal | Character | String | |
|---|---|---|---|---|---|---|
| Ada | `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` | `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 ( | ||
| item = iota | ||||||
| item | ||||||
| ... | ||||||
| )` | `interface{}` | |||||
| Rust | `char` | `String` | `bool` | `enum name { item« = value», item« = 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 | |||
| item «= value» | ||||||
| item «= *value» | ||||||
| ...* | ||||||
| End Enum` | [](variant-type) | |||||
| Visual Basic .NET | `Char` | `Object` | ||||
| Xojo | `Object` or `Variant` | |||||
| Python | `str` | `bool` | {{pre | 1= | `object` | |
| JavaScript | `String` | `Boolean` | `Object` | |||
| S-Lang | ||||||
| Fortran | `CLASS(*)` | |||||
| PHP | `string` | `bool` | (type declaration omitted) | |||
| Perl | `UNIVERSAL` | |||||
| Raku | `Char` | `Str` | `Bool` | `enum name1 item2 ...` | ||
| `enum name «:item1(value) :item2(value) ..»` | `Mu` | |||||
| Ruby | `String` | `Object` | `Object` | |||
| Scala | `Char` | `String` | `Boolean` | `object name extends Enumeration { | ||
| val item, item, ... = Value | ||||||
| }` | `Any` | |||||
| Seed7 | `char` | `string` | `boolean` | `const type: name is new enum | ||
| item, | ||||||
| item, | ||||||
| ... | ||||||
| end enum;` | ||||||
| Windows PowerShell | ||||||
| OCaml | `char` | `string` | `bool` | |||
| F# | `type name = item1 = value item2 = value ...` | `obj` | ||||
| Standard ML | ||||||
| Haskell (GHC) | `Char` | `String` | `Bool` | |||
| 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 | `String` |
- specifically, strings of arbitrary length and automatically managed.
- This language represents a boolean as an integer where false is represented as a value of zero and true by a non-zero value.
- All values evaluate to either true or false. Everything in
TrueClassevaluates to true and everything inFalseClassevaluates to false. - This language does not have a separate character type. Characters are represented as strings of length 1.
- Enumerations in this language are algebraic types with only nullary constructors
- The value of
nis provided by theSELECTED_INT_KINDintrinsic function.
Derived types
[[Array data type|Array]]
| fixed size array | dynamic size array | one-dimensional array | multidimensional array | one-dimensional array | multidimensional array |
|---|---|---|---|---|---|
| Ada | `array ( .. ) of ` | ||||
| or | |||||
| `array (*) of *` | `array (1 .. 1, 2 .. 2, ...) of ` | ||||
| or | |||||
| `array (1, 2, ...) of ` | `array ( range ) of ` | `array (1 range , 2 range , ...) of ` | |||
| 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]` | `type name[size1][size2]` | `type *name` | ||
| or within a block: | |||||
| `int n = ...; type name[n]` | |||||
| C++ (STL) | `«std::»array`(C++11) | `«std::»vector` | |||
| C# | `type[]` | `type[,,...]` | `System.Collections.ArrayList` | ||
| or | |||||
| `System.Collections.Generic.List` | |||||
| Java | `type[]` | `type[][]...` | `ArrayList or ArrayList` | ||
| D | `type[size]` | `type[size1][size2]` | `type[]` | ||
| Go | `[size]type` | `[size1][size2]...type` | `[]type` | `[][]type` | |
| Rust | `[type; size]` | `[[type; size1]; size2]` | `Vec` | `Vec` | |
| Swift | `[type]` or `Array` | `type` or `Array` | |||
| Objective-C | `NSArray` | `NSMutableArray` | |||
| JavaScript | `Array` | ||||
| Common Lisp | |||||
| Scheme | |||||
| ISLISP | |||||
| Pascal | `array[first..last] of type` | `array[first1..last1] of array[first2..last2] ... of type` | |||
| or | |||||
| ` array[first1..last1, first2..last2, ...] of type` | |||||
| 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` | |||||
| Standard ML | `type vector or type array` | ||||
| Haskell (GHC) | ` size-1) list_of_association_pairs` | `...), (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 size.` |
- In most expressions (except the
sizeofand&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. - The C-like
*type* x[]works in Java, however*type*[] xis the preferred form of array declaration. - Subranges are used to define the bounds of the array.
- JavaScript's array are a special kind of object.
- The
DEPENDING ONclause in COBOL does not create a true variable length array and will always allocate the maximum size of the array.
Other types
| Simple composite types | Algebraic data types | Unions | Records | Tuple expression |
|---|---|---|---|---|
| Ada | `type name is «abstract» «tagged» «limited» [recordfield : type;field : type;... | |||
| end record * null record]*` | combination of records, unions, and enumerations (as well as references to those, enabling recursive types). | `type name (variation : discrete_type) is recordcase variation iswhen choice_list =fieldname : type;...when choice_list =fieldname : 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;...};` | N/A}} | N/A}} | `union {type name;...};` |
| Objective-C | ||||
| C++ | `struct «name» {type name;...};` | `«std::»tuple` | ||
| C# | `struct name {type name;...}` | `(val, val, ... )` | N/A}} | |
| Java | ||||
| JavaScript | ||||
| D | `struct name {type name;...}` | `std.variant.Algebraic!(type,...)` | `union {type name;...}` | |
| Go | `struct { *«name» type*... | |||
| }` | ||||
| Rust | `struct name {name: type, ...}` | `(val, val, ... )` | `enum name { Foo(types), ...}` | `union name {name: type, ...}` |
| Swift | `struct name {*var name «: type»... | |||
| *}` | `(«name:» val, «name:» val, «name:» val, ... )` | `enum name { case Foo«(types)» case Bar «(types)» ... }` | ||
| Common Lisp | `(cons val val)` | |||
| Scheme | ||||
| ISLISP | ||||
| Pascal | `recordname: type;*... | |||
| *end` | `recordcase type ofvalue: (types);... | |||
| end` | ||||
| Visual Basic | ||||
| Visual Basic .NET | `Structure nameDim name As *type*... | |||
| End Structure` | `(val, val, ... )` | |||
| Python | `«(»val, val, val, ... «)»` | |||
| S-Lang | `struct {name [=value], ...}` | |||
| Fortran | `TYPE nametype :: *name... | |||
| *END TYPE` | ||||
| PHP | ||||
| Perl | N/A}} | |||
| Raku | ||||
| Ruby | ||||
| Scala | `case class name(«var» name: type, ...)` | `(val, val, val, ... )` | `abstract class namecase class Foo(«parameters») extends namecase class Bar(«parameters») extends *name*...` | |
| or | ||||
| `abstract class namecase object Foo extends namecase object Bar extends *name*...` | ||||
| or a combination of case classes and case objects | ||||
| Windows PowerShell | ||||
| OCaml | `type name = {«mutable» name : type;...}` | `«(»val, val, val, ... «)»` | `type name = Foo «of type» Bar «of type» ...` | N/A}} |
| F# | ||||
| Standard ML | `type name = {name : type,...}` | `(val, val, val, ... )` | `datatype name = Foo «of type» Bar «of type» ...` | |
| Haskell | `data Name = Constr {name :: type,...}` | `data Name = Foo «types» Bar «types» ...` | ||
| COBOL | `.....` | `name REDEFINES variable type.` |
- Only classes are supported.
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.- pair only
- 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.
- Enumerations in this language are algebraic types with only nullary constructors
Variable and constant declarations
| variable | constant | type synonym | |
|---|---|---|---|
| Ada | Ada declaration | [e]}} | `identifier : constant type := final_value` |
| ALGOL 68 | `modename name« := initial_value»;` | `modename name = value;` | |
| C (C99) | `type name« = initial_value»;` | `enum{ name = value };` | |
| 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, ... ;` | |||
| D | `type name« = initial_value»;` | ||
| or | |||
| `auto name = value;` | `const type name = value;` | ||
| or | |||
| `immutable type name = value;` | |||
| 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` | ||
| Racket | `(define name expression)` | ||
| Rust | `let mut name«: type»« = initial_value»;` | ||
| `static mut NAME: type = value;` | `let name«: type»« = initial_value»;` | ||
| `const NAME: type = value;` | |||
| `static NAME: type = value;` | |||
| Swift | `var name «: type»« = initial_value»` | `let name «: type» = value` | |
| Common Lisp | `(defparameter name initial-value)` | ||
| or | |||
| `(defvar name initial-value)` | `(defconstant name value)` | ||
| Scheme | `(define name initial_value)` | ||
| ISLISP | `(defglobal name initial_value)` | ||
| or | |||
| `(defdynamic name initial_value)` | `(defconstant name value)` | ||
| Pascal | `name: type« = initial_value»` | `name = value` | |
| Visual Basic | `Dim name «As type»` | See notes to left. | |
| Visual Basic .NET | The variable declaration syntax of VB.NET is unusually difficult to precisely describe. | `Imports synonym = type` | |
| Xojo | `Dim name «As type»« = initial_value»` | ||
| Python | `name«: type» = initial_value` | rowspan=2 | |
| CoffeeScript | `name = initial_value` | ||
| S-Lang | `name = initial_value;` | ||
| Fortran | `type :: name` | `type, PARAMETER :: name = value` | |
| PHP | `$name = initial_value;` | `define("name", value); | |
| const name = value (5.3+)` | |||
| Perl | Perl's my keyword | [c]}} | `use constant name = value;` |
| Raku | Perl's my keyword | [c]}} | `«my «type»» constant name = value;` |
| Ruby | `name = initial_value` | `Name = value` | |
| Scala | `var name«: type» = initial_value` | `val name«: type» = value` | |
| Windows PowerShell | `«[type]» $name = initial_value` | ||
| Bash shell | `name=initial_value` | ||
| OCaml | ML ref | [d]}} | `let name «: type» = value` |
| F# | `let mutable name «: type» = value` | ||
| Standard ML | ML ref | [d]}} | `val name «: type» = value` |
| Haskell | `«name::type;» name = value` | ||
| 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.` | |
| Mathematica | `name=initial_value` |
- Pascal has declaration blocks. See functions.
- Types are just regular objects, so you can just assign them.
- In Perl, the "my" keyword scopes the variable into the block.
- 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. - 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.
- In Rust, if no initial value is given to a
letorlet mutvariable and it is never assigned to later, there is an "unused variable" warning. If no value is provided for aconstorstaticorstatic mutvariable, there is an error. There is a "non-upper-case globals" error for non-uppercaseconstvariables. After it is defined, astatic mutvariable can only be assigned to in anunsafeblock or function.
[[Control flow]]
[[Conditional (programming)|Conditional]] statements
| if | else if | select case | conditional expression | if | else if | select case | conditional expression | ||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| Ada | `if condition thenstatements | ||||||||||
| «elsestatements» | |||||||||||
| end if` | `if condition thenstatements | ||||||||||
| elsif condition thenstatements | |||||||||||
| ... | |||||||||||
| «elsestatements» | |||||||||||
| end if` | `case expression iswhen value_list = statementswhen value_list = *statements*...«when others = statements» | ||||||||||
| end case` | `(if condition thenexpression | ||||||||||
| «elsif condition thenexpression» | |||||||||||
| ... | |||||||||||
| elseexpression | |||||||||||
| )` | |||||||||||
| or | |||||||||||
| `(case expression iswhen value_list = expressionwhen value_list = *expression*...«when others = expression» | |||||||||||
| )` | |||||||||||
| Seed7 | `if condition thenstatements | ||||||||||
| «elsestatements» | |||||||||||
| end if` | `if condition thenstatements | ||||||||||
| elsif condition thenstatements | |||||||||||
| ... | |||||||||||
| «elsestatements» | |||||||||||
| end if` | `case expression ofwhen set1 : *statements*...«otherwise: statements» | ||||||||||
| end case` | |||||||||||
| Modula-2 | `if condition thenstatements | ||||||||||
| «elsestatements» | |||||||||||
| end` | `if condition thenstatements | ||||||||||
| elsif condition thenstatements | |||||||||||
| ... | |||||||||||
| «elsestatements» | |||||||||||
| end` | `case expression ofcaseLabelList : 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` | valueIfTrue | valueIfFalse ) | ||||||
| ALGOL 68 | |||||||||||
| (brief form) | statements « | statements» ) | statements | : condition | statements ) | statements,... « | statements» ) | ||||
| APL | `:If *condition*instructions | ||||||||||
| «:Elseinstructions» | |||||||||||
| :EndIf` | `:If *condition*instructions | ||||||||||
| :ElseIf *condition*instructions | |||||||||||
| ... | |||||||||||
| «:Elseinstructions» | |||||||||||
| :EndIf` | `:Select expression:Case *case1instructions...«:Elseinstructions*» | ||||||||||
| :EndSelect` | `{condition:valueIfTrue ⋄ valueIfFalse}` | ||||||||||
| 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»` | `if (condition) instructions | ||||||||||
| else if (condition) instructions | |||||||||||
| ... | |||||||||||
| «else instructions»` | `switch (variable) | ||||||||||
| { case case:instructions«break_or_jump_statement»...«default:*instructions*break_or_jump_statement» | |||||||||||
| }` | `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` | ||||||||||
| Racket | `(when testexpression expressions)` | ||||||||||
| or | |||||||||||
| `(unless condition expressions)` | `(cond` | ||||||||||
| ` [testexpression expressions]` | |||||||||||
| ` [testexpression expressions]` | |||||||||||
| ` ...` | |||||||||||
| ` [else expressions])` | `(case expression [(case1) expressions]` | ||||||||||
| ` [(case2) expressions]` | |||||||||||
| ` ...` | |||||||||||
| ` [else expressions])` | `(if testexpression expressioniftrue expressioniffalse)` | ||||||||||
| 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 | ||||||||||
| «elseinstructions»` | `if *condition*instructions | ||||||||||
| elsif *condition*instructions | |||||||||||
| ... | |||||||||||
| «elseinstructions» | |||||||||||
| end` | `case variablewhen *case1instructions...«elseinstructions*» | ||||||||||
| end` | `condition [?]() valueIfTrue [:]() valueIfFalse` | ||||||||||
| Scala | `if (condition) {instructions} | ||||||||||
| «else {instructions}»` | `if (condition) {instructions} | ||||||||||
| else if (condition) {instructions} | |||||||||||
| ... | |||||||||||
| «else {instructions}»` | `expression match { case pattern1 = expressioncase pattern2 = *expression*...«case _ = expression» | ||||||||||
| }` | `if (condition) valueIfTrue else valueIfFalse` | ||||||||||
| Smalltalk | `condition ifTrue:trueBlock | ||||||||||
| «ifFalse:falseBlock» | |||||||||||
| end` | `condition ifTrue: trueBlock ifFalse: falseBlock` | ||||||||||
| Common Lisp | `(when conditioninstructions)` | ||||||||||
| 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 begininstructions | ||||||||||
| end | |||||||||||
| «else begininstructions | |||||||||||
| end»'` | `if condition then begininstructions | ||||||||||
| end | |||||||||||
| else if condition then begininstructions | |||||||||||
| end | |||||||||||
| ... | |||||||||||
| «else begininstructions | |||||||||||
| end»` | `case variable ofcase1: *instructions*...«else: instructions» | ||||||||||
| end` | |||||||||||
| Visual Basic | `If condition Theninstructions | ||||||||||
| «Elseinstructions» | |||||||||||
| End If` | |||||||||||
| Single-line, when `instructions` are `instruction : instruction : ...`: | |||||||||||
| `If condition Then instructions «Else instructions»` | `If condition Theninstructions | ||||||||||
| ElseIf condition Theninstructions | |||||||||||
| ... | |||||||||||
| «Elseinstructions» | |||||||||||
| 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» variableCase *case_patterninstructions...«Case Elseinstructions*» | ||||||||||
| End Select` | `IIf(condition, valueIfTrue, valueIfFalse)` | ||||||||||
| Visual Basic .NET | `If(condition, valueIfTrue, valueIfFalse)` | ||||||||||
| Xojo | |||||||||||
| Python | `if condition : | ||||||||||
| instructions | |||||||||||
| «else: | |||||||||||
| instructions»` | `if condition : | ||||||||||
| instructions | |||||||||||
| elif condition : | |||||||||||
| instructions | |||||||||||
| ... | |||||||||||
| «else: | |||||||||||
| instructions»` | Python 3.10+: | ||||||||||
| `match variable: | |||||||||||
| case case1: | |||||||||||
| instructions | |||||||||||
| case case2: | |||||||||||
| 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) THENinstructions | ||||||||||
| ELSEinstructions | |||||||||||
| ENDIF` | `IF (condition) THENinstructions | ||||||||||
| ELSEIF (condition) THENinstructions | |||||||||||
| ... | |||||||||||
| ELSEinstructions | |||||||||||
| ENDIF` | `SELECT CASE(variable)CASE (case1)*instructions*...CASE DEFAULTinstructions | ||||||||||
| END SELECT` | |||||||||||
| Forth | `condition IF instructions « ELSE instructions» THEN` | `condition IF instructions ELSE condition IF instructions THEN THEN` | `value CASEcase OF instructions ENDOFcase OF instructions ENDOFdefault 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»` | `if condition then valueIfTrue else valueIfFalse` | |||||||
| F# | Lightweight syntax mode: | Lightweight syntax mode: | |||||||||
| Either on a single line or with indentation as shown below: | |||||||||||
| `if condition then | |||||||||||
| instructions | |||||||||||
| elif condition then | |||||||||||
| instructions | |||||||||||
| ... | |||||||||||
| «else | |||||||||||
| 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 ofpattern1 = expression pattern2 = *expression*...« _ = expression»` | ||||||||||
| Haskell (GHC) | `if condition then expression else expression` | ||||||||||
| or | |||||||||||
| `when condition (do instructions)` | |||||||||||
| or | |||||||||||
| `unless notcondition (do instructions)` | 2}} condition = expression otherwise = expression` | `case value of { pattern1 - expression;pattern2 - expression;...«_ - expression» | |||||||||
| }` | |||||||||||
| Bash shell | `if condition-command; thenexpression | ||||||||||
| «elseexpression» | |||||||||||
| fi` | `if condition-command; thenexpression | ||||||||||
| elif condition-command; thenexpression | |||||||||||
| «elseexpression» | |||||||||||
| fi` | `case "$variable" in"$condition1" )command..."$condition2" )command... | ||||||||||
| esac` | |||||||||||
| CoffeeScript | `if condition then expression «else expression»` | ||||||||||
| or | |||||||||||
| `if conditionexpression | |||||||||||
| «elseexpression»` | |||||||||||
| or | |||||||||||
| `expression if condition` | |||||||||||
| or | |||||||||||
| `unless *condition*expression | |||||||||||
| «elseexpression»` | |||||||||||
| or | |||||||||||
| `expression unless condition` | `if condition then expression else if condition then expression «else expression»` | ||||||||||
| or | |||||||||||
| `if *condition*expression | |||||||||||
| else if conditionexpression | |||||||||||
| «elseexpression»` | |||||||||||
| or | |||||||||||
| `unless *condition*expression | |||||||||||
| else unless conditionexpression | |||||||||||
| «elseexpression»` | `switch expressionwhen condition then expressionelse expression` | ||||||||||
| or | |||||||||||
| `switch expressionwhen *condition*expression«elseexpression»` | All conditions are expressions. | ||||||||||
| COBOL | `IF condition «THEN»expression | ||||||||||
| «ELSEexpression».` | `EVALUATE expression «ALSO expression...»WHEN case-or-condition «ALSO case-or-condition...»expression...«WHEN OTHERexpression» | ||||||||||
| 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*» | ||||||||||
| }` | All conditions are expressions |
- 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.
- This is pattern matching and is similar to select case but not the same. It is usually used to deconstruct algebraic data types.
- In languages of the Pascal family, the semicolon is not part of the statement. It is a separator between statements, not a terminator.
END-IFmay be used instead of the period at the end.- 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{}).
[[Control flow#Loops|Loop statements]]
| while loop | do while loop | (count-controlled) for loop | foreach |
|---|---|---|---|
| Ada | `while condition loopstatements | ||
| end loop` | `loopstatementsexit when not condition | ||
| end loop` | `for index in «reverse» [first .. last discrete_type] loopstatements | ||
| end loop` | |||
| 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` | `:Repeatstatements | ||
| :Until condition` | `:For var«s» :In *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 | |
| 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 | Since EcmaScript 2015: | |
| PHP | `foreach (range(first, last) as $i) instructions` | ||
| or | |||
| `for ($i = first; $i | `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 | |
| 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 .. | |||
| 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 | |||
| 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 | |||
| Ruby | `while *condition*instructions | ||
| end` | |||
| or | |||
| `until *notcondition*instructions | |||
| end` | `begininstructions | ||
| end while condition` | |||
| or | |||
| `begininstructions | |||
| 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 }` | |||
| Bash shell | `while condition ;doinstructions | ||
| done` | |||
| or | |||
| `until notcondition ;doinstructions | |||
| done` | 2}}instructions | ||
| done` | |||
| Scala | `while (condition) { instructions }` | `do { instructions } while (condition)` | `for (i { instructions })` |
| Smalltalk | `conditionBlock whileTrue:loopBlock` | `loopBlock doWhile:conditionBlock` | `first to: last do:loopBlock` |
| Common Lisp | `(loopwhile conditiondoinstructions)` | ||
| or | |||
| `(do () (notcondition)instructions)` | `(loopdoinstructionswhile condition)` | `(loopfor i from first to last «by 1»doinstructions)` | |
| or | |||
| `(dotimes (i N)instructions)` | |||
| or | |||
| `(do ((i first last)) | |||
| instructions)` | |||
| Scheme | `(do () (notcondition) instructions)` | ||
| or | |||
| ` condition (begin instructions (loop))))` | `instructions (if condition (loop))))` | `(do ((i first last)) instructions)` | |
| or | |||
| ` first{{codett | 2=scheme | 1)) (if ( | |
| ISLISP | `(while condition instructions)` | ` instructions (if condition ` | ` first last)) instructions)` |
| Pascal | `while condition do begininstructions | ||
| end` | `repeatinstructions | ||
| until notcondition;` | 2}}instructions | ||
| end;` | |||
| 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) | `Doinstructions | ||
| Loop While condition` | |||
| or | |||
| `Doinstructions | |||
| Loop Until notcondition` | `i` must be declared beforehand. | ||
| Visual Basic .NET | `For i« As type» = first To last« Step 1»instructions | ||
| Next« i»` | `For Each item« As type» In *set*instructions | ||
| Next« item»` | |||
| Xojo | `While *condition*instructions | ||
| Wend` | `Do Until *notcondition*instructions | ||
| Loop` | |||
| or | |||
| `Doinstructions | |||
| Loop Until notcondition` | |||
| Python | `while condition : | ||
| instructions | |||
| «else: | |||
| instructions»` | Python 3.x: | ||
| `first, last+1): | |||
| instructions | |||
| «else: | |||
| instructions»` | |||
| Python 2.x: | |||
| `first, last+1): | |||
| instructions | |||
| «else: | |||
| instructions»` | |||
| S-Lang | `while (condition) { instructions } «then optional-block»` | `do { instructions } while (condition) «then optional-block»` | `for (i = first; i |
| Fortran | `DO WHILE (condition)instructions | ||
| ENDDO` | `DOinstructionsIF (condition) EXIT | ||
| ENDDO` | 2}}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` | |
| F# | `while condition do | ||
| instructions` | Tab}}instructions` | ||
| Standard ML | `while condition do ( instructions )` | colspan=2 | `Array.app (fn item = instructions) array` |
| or | |||
| `app (fn item = instructions) list` | |||
| Haskell (GHC) | colspan=2 | `Control.Monad.forM_ [first..last] (\i - do instructions)` | `Control.Monad.forM_list (\item - do instructions)` |
| Eiffel | `fromsetup | ||
| untilcondition | |||
| loopinstructions | |||
| 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]` | |||
| COBOL | `PERFORM procedure-1 «THROUGH procedure-2» condition` | ||
| or | |||
| ` *condition*expression | |||
| END-PERFORM` | `PERFORM procedure-1 «THROUGH procedure-2» condition` | ||
| or | |||
| ` *condition*expression | |||
| END-PERFORM` | `PERFORM procedure-1 «THROUGH procedure-2» VARYING i FROM first BY increment UNTIL i last` | ||
| or | |||
| `PERFORM VARYING i FROM first BY increment UNTIL i *last*expression | |||
| END-PERFORM` | |||
| Rust | `while condition { expression | ||
| }` | `loop { expressionif condition { break;} | ||
| }` | `for i in first..last+1 { expression | ||
| }` | |||
| or | |||
| `for i in first..=last { expression | |||
| }` |
- "
stepn" is used to change the loop interval. If "step" is omitted, then the loop interval is 1. - This implements the universal quantifier ("for all" or ∀) as well as the existential quantifier ("there exists" or ∃).
THRUmay be used instead ofTHROUGH.- may be used instead of ``.
- Type of set expression must implement trait
std::iter::IntoIterator.
[[Exception handling|Exceptions]]
| throw | handler | assertion | |||||||
|---|---|---|---|---|---|---|---|---|---|
| Ada | `raise exception_name «with string_expression»` | `beginstatements | |||||||
| exceptionwhen exception_list1 = statements;when exception_list2 = statements; | |||||||||
| ...«when others = statements;» | |||||||||
| end` | |||||||||
| APL | `«string_expression» ⎕SIGNAL number_expression` | `:Trap *number«s»_expression*statements | |||||||
| «:Case *number«s»_expression*statements» | |||||||||
| ... | |||||||||
| «:Else *number«s»_expression*statements» | |||||||||
| :EndTrap` | |||||||||
| C (C99) | `longjmp(state, exception);` | `switch (setjmp(state)) { case 0: instructions break; case exception: instructions ... }` | |||||||
| 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 }»` | `condition)` | ||||||||
| Objective-C | `@throw exception;` | `@try { instructions } @catch (exception) { instructions } ... «@finally { instructions }»` | |||||||
| Swift | `throw exception` (2.x) | `do { try expression ... instructions } catch exception { instructions } ...` (2.x) | |||||||
| Perl | `die exception;` | `eval { instructions instructions }` | |||||||
| Raku | `try { instructions CATCH { when exception { instructions } ...}}` | ||||||||
| Ruby | `raise exception` | `begininstructions | |||||||
| rescue *exception*instructions | |||||||||
| ... | |||||||||
| «elseinstructions» | |||||||||
| «ensureinstructions» | |||||||||
| end` | |||||||||
| Smalltalk | `exception raise` | `instructionBlock on: exception do: handlerBlock` | |||||||
| Common Lisp | `(error "exception")` | ||||||||
| or | |||||||||
| `(error*type*arguments)` | |||||||||
| or | |||||||||
| `(error (make-condition*type*arguments))` | `(handler-case(progn instructions)(exception instructions)...)` | ||||||||
| or | |||||||||
| `(handler-bind(condition(lambdainstructions«invoke-restart restart args»)) | |||||||||
| ...)` | |||||||||
| 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` | ` *Try**OneInstruction | |||||||
| .Catch .NumberCase SOME_ERRORNUMBER*instructions | |||||||||
| ` | |||||||||
| Visual Basic .NET | `Throw exception` | ||||||||
| or | |||||||||
| `Error errorcode` | `Tryinstructions | ||||||||
| Catch« name As exception»« When condition»instructions | |||||||||
| ... | |||||||||
| «Finallyinstructions» | |||||||||
| End Try` | |||||||||
| Xojo | `Raise exception` | `Tryinstructions | |||||||
| Catch *«exception»*instructions | |||||||||
| ... | |||||||||
| «Finallyinstructions» | |||||||||
| End Try` | |||||||||
| Python | `raise exception` | `try: | |||||||
| instructions | |||||||||
| except «exception»: | |||||||||
| instructions | |||||||||
| ... | |||||||||
| «else: | |||||||||
| instructions» | |||||||||
| «finally: | |||||||||
| instructions»` | |||||||||
| Fortran | colspan=3 | ||||||||
| Forth | `code THROW` | `xt CATCH ( code or 0 )` | |||||||
| OCaml | `raise exception` | `try expression with pattern - expression ...` | |||||||
| 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` | |||||||||
| COBOL | ` exception` | ` class-name.` | |||||||
| or | |||||||||
| ` class-name.` | |||||||||
| or | |||||||||
| ` exception-name «FILE file-name».` | |||||||||
| or | |||||||||
| ` exception-name «FILE file-name».` | |||||||||
| Rust | last1=Klabnik | first1=Steve | last2=Nichols | first2=Carol | title=The Rust Programming Language | url=https://doc.rust-lang.org/book/title-page.html | chapter=Error Handling | chapter-url=https://doc.rust-lang.org/book/ch09-00-error-handling.html}} | `assert!(condition)` |
- Common Lisp allows
with-simple-restart,restart-caseandrestart-bindto define restarts for use withinvoke-restart. Unhandled conditions may cause the implementation to show a restarts menu to the user before unwinding the stack. - Uncaught exceptions are propagated to the innermost dynamically enclosing execution. Exceptions are not propagated across tasks (unless these tasks are currently synchronised in a rendezvous).
Other control flow statements
| exit block (break) | continue | label | branch (goto) | return value from generator |
|---|---|---|---|---|
| Ada | `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; ...*` | ||||
| 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»;` | rowspan=2 | |
| 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) | colspan=2 | `label:` | `goto label;` | rowspan=4 |
| Pascal (FPC) | `break;` | `continue;` | ||
| Visual Basic | `Exit block`Alternatively, for methods, | |||
| `Return` | `label:` | `GoTo label` | ||
| Xojo | `Continue block` | |||
| Visual Basic .NET | `Yield value` | |||
| Python | `break` | `continue` | colspan=2 | `yield value` |
| RPG IV | `LEAVE;` | `ITER;` | ||
| S-Lang | `break;` | `continue;` | ||
| Fortran | `EXIT` | `CYCLE` | `label` | `GOTO label` |
| Ruby | `break` | `next` | ||
| Windows PowerShell | `break «label»` | `continue` | ||
| OCaml | rowspan=4 colspan=4 | |||
| F# | ||||
| Standard ML | ||||
| Haskell (GHC) | ||||
| COBOL | `EXIT PERFORM` or `EXIT PARAGRAPH` or `EXIT SECTION` or `EXIT.` | `EXIT PERFORM CYCLE` | `label «SECTION».` | `GO TO label` |
- Pascal has declaration blocks. See functions.
- label must be a number between 1 and 99999.
[[Subroutine|Function]]s
See reflective programming for calling and declaring functions by strings.
| calling a function | basic/void function | value-returning function | required main function |
|---|---|---|---|
| Ada | `foo «(parameters)»` | `procedure foo «(parameters)» is begin statements end foo` | `function foo «(parameters)» return type is begin statements end foo` |
| ALGOL 68 | `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; }` |
| Objective-C | |||
| C++ (STL) | |||
| Java | ` { instructions }` | ||
| or | |||
| `... args) { instructions }` | |||
| D | ` { instructions}` | ||
| or | |||
| ` { instructions}` | |||
| or | |||
| ` { instructions}` | |||
| or | |||
| ` { instructions}` | |||
| C# | Same as above; alternatively, if only one statement: | Same as above; alternatively, if simple enough to be an expression: | |
| May instead return `int`. | |||
| (starting with C# 7.1:) May return `Task` or , and if so, may be `async`. | |||
| JavaScript | `function foo(«parameters») { instructions }` | ||
| or | |||
| `«parameters») { instructions }` | |||
| or | |||
| `"«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 | |||
| `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;» | |
| «labellabel declarations» | |||
| «constconstant declarations» | |||
| «typetype declarations» | |||
| «var*variable declarations» | |||
| «local function declarations»* | |||
| begininstructions | |||
| end;` | `function foo«(parameters)»: type; «forward;» | ||
| «labellabel declarations» | |||
| «constconstant declarations» | |||
| «typetype declarations» | |||
| «var*variable declarations» | |||
| «local function declarations»* | |||
| begininstructions;foo := value | |||
| end;` | |||
| Visual Basic | `Foo(«parameters»)` | `Sub Foo«(parameters)»instructions | |
| End Sub` | `Function Foo«(parameters)»« As* type»*instructionsFoo = value | ||
| End Function` | |||
| Visual Basic .NET | Same as above; alternatively: | `instructions | |
| End Sub`or | |||
| `instructions | |||
| End Function` | |||
| Xojo | |||
| Python | `foo(«parameters»)` | `def foo(«parameters»): | |
| instructions` | `def foo(«parameters»): | ||
| instructions | |||
| return value` | |||
| S-Lang | `foo(«parameters» «;qualifiers»)` | `define foo («parameters») { instructions }` | `define foo («parameters») { instructions ... return value; }` |
| Fortran | `foo («arguments») | ||
| CALL sub_foo («arguments»)` | `SUBROUTINE sub_foo («arguments»)*instructions | ||
| *END SUBROUTINE` | `type FUNCTION foo («arguments»)*instructions...foo = value* | ||
| END FUNCTION` | |||
| Forth | `«parameters» FOO` | ` ( before -- ) »instructions | |
| ;` | ` ( before -- after ) »instructions | ||
| ;` | |||
| PHP | `foo(«parameters»)` | `function foo(«parameters») { instructions }` | `function foo(«parameters») { instructions ... return value; }` |
| Perl | `foo(«parameters»)` | ||
| or | |||
| `&foo«(parameters)»` | `parameters) = @_;» instructions }` | `parameters) = @_;» instructions... «return» value; }` | |
| Raku | `foo(«parameters»)` | ||
| or | |||
| `&foo«(parameters)»` | `parameters) { instructions }` | `«our «type» »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 }` |
| Scala | `foo«(parameters)»` | `def foo«(parameters)»«: Unit =» { instructions }` | `def foo«(parameters)»«: type» = { instructions ... «return» value }` |
| Windows PowerShell | `foo «parameters»` | `function foo { instructions };` | |
| or | |||
| `function foo { «param(parameters)» instructions }` | `function foo «(parameters)» { instructions ... return value };` | ||
| or | |||
| `function foo { «param(parameters)» instructions ... return value }` | |||
| Bash shell | `foo «parameters»` | `function foo instructions | |
| }` | |||
| or | |||
| `foo () instructions | |||
| }` | `function foo instructionsreturn «exit_code» | ||
| }` | |||
| or | |||
| `foo () { instructionsreturn «exit_code» | |||
| }` | |||
| OCaml | `foo parameters` | `let «rec» foo parameters = instructions` | `let «rec» foo parameters = instructions... return_value` |
| F# | ` = instructions` | ||
| Standard ML | `fun foo parameters = ( instructions )` | `fun foo parameters = ( instructions... return_value )` | |
| Haskell | Tab}}instructions` | Tab}}instructions | |
| return value` | `«main :: IO ()» | ||
| main = do instructions` | |||
| Eiffel | `foo («parameters»)` | `foo («parameters»)requirepreconditionsdoinstructionsensurepostconditionsend` | `foo («parameters»): typerequirepreconditionsdoinstructionsResult := valueensurepostconditionsend` |
| CoffeeScript | `foo()` | ` value` | |
| `foo parameters` | `foo = ( parameters ) - value` | ||
| COBOL | `CALL "foo" «USING *parameters»«exception-handling» | ||
| «END-CALL»*` | `«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»)»` |
- Pascal requires "
forward;" for forward declarations. - Eiffel allows the specification of an application's root class and feature.
- In Fortran, function/subroutine parameters are called arguments (since
PARAMETERis a language keyword); theCALLkeyword is required for subroutines. - Instead of using
"foo", a string variable may be used instead containing the same value.
[[Type conversion]]s{{anchor|Data conversions}}
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 | `Integer'Value (string_expression)` | `Long_Integer'Value (string_expression)` | `Float'Value (string_expression)` | `Integer'Image (integer_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` | |
| C (C99) | `integer = atoi(string);` | atol]](string);` | `float = atof(string);` | `sprintf(string, "%i", integer);` | |
| Objective-C | `integer = [string intValue];` | `long = [string longLongValue];` | `float = [string doubleValue];` | 2=objc | [NSString stringWithFormat:@"%i",}} integer];` |
| C++ (STL) | `«std::»istringstream(string) number;` | `«std::»ostringstream o; o | |||
| 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);` | |||||
| JavaScript | `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)` | |||||
| Rust | `string.parse::()` | ||||
| `i32::from_str(string)` | `string.parse::()` | ||||
| `i64::from_str(string)` | `string.parse::()` | ||||
| `f64::from_str(string)` | `integer.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 ))` | `(setf float (convert string ))` | `(setf string (convert number ))` | ||
| Pascal | `integer := StrToInt(string);` | `float := StrToFloat(string);` | `string := IntToStr(integer);` | ||
| 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);` | 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 | `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.toFloat``double = 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` | ||
| 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` | ||
| Haskell (GHC) | `number = read string` | `string = show number` | |||
| COBOL | `string) TO number` | `MOVE number TO numeric-edited` |
- JavaScript only uses floating point numbers so there are some technicalities.
- Perl doesn't have separate types. Strings and numbers are interchangeable.
NUMVAL-CorNUMVAL-Fmay be used instead ofNUMVAL.str::parseis available to convert any type that has an implementation of thestd::str::FromStrtrait. Bothstr::parseandFromStr::from_strreturn aResultthat contains the specified type if there is no error. The turbofish (::) onstr::parsecan be omitted if the type can be inferred from context.
[[Standard streams|Standard stream I/O]]
| read from | write to | stdin | stdout | stderr |
|---|---|---|---|---|
| Ada | `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));` | |||
| APL | `x←⎕` | `⎕←x` | `⍞←x` | |
| C (C99) | `scanf(format, &x);` | |||
| or | ||||
| `fscanf(stdin, format, &x);` | `printf(format, x);` | |||
| or | ||||
| `fprintf(stdout, format, x);` | `fprintf(stderr, format, x);` | |||
| 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 | `«std::»cerr | ||
| 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)` | (format error-output | lisp}} format x)` | ||
| Scheme (R6RS) | (define x (read-line)) | `(display x)` | ||
| or | ||||
| ` format x)` | (format (current-error-port) | scheme}} format x)` | ||
| ISLISP | `(setf x (read-line))` | ` format x)` | ` format x)` | |
| Pascal | `read(x);` | |||
| or | ||||
| `readln(x);` | `write(x);` | |||
| or | ||||
| `writeln(x);` | `write(stderr, x);` | |||
| or | ||||
| `writeln(stderr, x);` | ||||
| Visual Basic | `Input« prompt,» x` | `Print x` | ||
| or | ||||
| `? x` | ||||
| Visual Basic .NET | `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)` | ||||
| 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)` | ` x` | |||
| or | ||||
| `sys.stderr.write(x)` | ||||
| Python 3.x | `x = input(«prompt»)` | `print(x«, end=""»)` | `print(x«, 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` | `WRITE(,format) expressions* ` | |||
| or | ||||
| `WRITE(OUTPUT_UNIT,format) expressions` | `WRITE(ERROR_UNIT,format) expressions` | |||
| 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 = ;` | `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` | ` str)` | |
| Haskell (GHC) | `x getLine` | `print x` | ||
| or | ||||
| `putStrLn str` | `hPrint stderr x` | |||
| or | ||||
| `hPutStrLn stderr str` | ||||
| COBOL | `ACCEPT x` | `DISPLAY x` |
- ALGOL 68 additionally as the "unformatted" transput routines:
read,write,get, andput. gets(x)andfgets(x, *length*, stdin)read unformatted text from stdin. Use of gets is not recommended.puts(x)andfputs(x, stdout)write unformatted text to stdout.fputs(x, stderr)writes unformatted text to stderr- are defined in the module.
Reading [[command-line argument]]s
| Argument values | Argument counts | Program name / Script name | ||||
|---|---|---|---|---|---|---|
| Ada | `Argument (n)` | `Argument_Count` | ||||
| C (C99) | `argv[n]` | `argc` | ||||
| Objective-C | ||||||
| C++ | ||||||
| C# | `args[n]` | `args.Length` | ||||
| Java | `args.length` | |||||
| D | first argument | |||||
| JavaScript | ||||||
| Windows Script Host implementation | `WScript.Arguments(n)` | `WScript.Arguments.length` | ||||
| Go | `os.Args[n]` | `len(os.Args)` | ||||
| Rust | `std::env::args().nth(n)` | |||||
| `std::env::args_os().nth(n)` | ||||||
| Swift | `Process.arguments[n]` or | |||||
| `Process.unsafeArgv[n]` | `Process.arguments.count` or | |||||
| `Process.argc` | ||||||
| Common Lisp | ||||||
| Scheme (R6RS) | ||||||
| ISLISP | ||||||
| Pascal | `ParamStr(n)` | `ParamCount` | ||||
| Visual Basic | `Command` | |||||
| Visual Basic .NET | `CmdArgs(n)` | `CmdArgs.Length` | ||||
| Xojo | `System.CommandLine` | (string parsing) | ||||
| Python | `sys.argv[n]` | `len(sys.argv)` | ||||
| S-Lang | `__argv[n]` | `__argc` | ||||
| Fortran | 2}}CALL GET_COMMAND_ARGUMENT (i,argv(i)) | |||||
| ENDDO` | `argc = COMMAND_ARGUMENT_COUNT ()` | |||||
| PHP | `$argv[n]` | `$argc` | ||||
| Bash shell | `$n ($1, $2, $3, ...)` | |||||
| `$@` (all arguments) | `$#` | |||||
| Perl | `$ARGV[n]` | |||||
| Raku | `@ARGS[n*]` | |||||
| Ruby | `ARGV[n]` | `ARGV.size` | ||||
| Windows PowerShell | `$args[n]` | `$args.Length` | ||||
| OCaml | `Sys.argv.(n)` | `Array.length Sys.argv` | ||||
| F# | `args.[n]` | `args.Length` | ||||
| Standard ML | ||||||
| Haskell (GHC) | {{code | lang=haskell | do { args | {{code | lang=haskell | do { args |
| COBOL |
- In Rust,
std::env::argsandstd::env::args_osreturn iterators,std::env::Argsandstd::env::ArgsOsrespectively.Argsconverts each argument to aStringand it panics if it reaches an argument that cannot be converted to UTF-8.ArgsOsreturns a non-lossy representation of the raw strings from the operating system (std::ffi::OsString), which can be invalid UTF-8. - In Visual Basic, command-line arguments are not separated. Separating them requires a split function
Split(*string*). - 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
ACCEPTstatements.
Execution of commands
| Shell command | Execute program | Replace current program with new executed program |
|---|---|---|
| Ada | Not part of the language standard. Commonly done by compiler provided packages or by interfacing to C or POSIX. | |
| C | `system("command");` | |
| 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)` | |
| 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");` | |
| Java | `Runtime.exec(command);` | |
| or | ||
| `new ProcessBuilder(command).start();` | ||
| JavaScript | ||
| Windows Script Host implementation | `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, ...` |
| Standard ML | `OS.Process.system command` | `Unix.execute (path, args)` |
| Haskell (GHC) | `System.system command` | `System.Process.runProcess path args ...` |
| Perl | `system(command)` | |
| or | ||
| `$output = `command`` | ||
| or | ||
| `$output = qx(command)` | ||
| Ruby | `system(command)` | |
| or | ||
| `output = `command`` | ||
| 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", ...])` | |
| S-Lang | `system(command)` | |
| Fortran | `CALL EXECUTE_COMMAND_LINE (COMMAND «, WAIT» «, EXITSTAT» «, CMDSTAT» «, CMDMSG»)` | |
| Windows PowerShell | [Diagnostics.Process]::Start(command) | `«Invoke-Item »program arg1 arg2 ...` |
| Bash shell | `output=`command`` | |
| or | ||
| `output=$(command)` | `program arg1 arg2 ...` |
Fortran 2008 or newer.
References
References
- "Reference Manual".
- "Common Lisp HyperSpec (TM)". lispworks.com.
- "www.islisp.info: Specification". islisp.info.
- "selected_int_kind in Fortran Wiki". fortranwiki.org.
- "Erlang {{--}} Types and Function Specifications". erlang.org.
- "Erlang {{--}} Advanced". erlang.org.
- [https://www.mozilla.org/js/language/E262-3.pdf 8.5 The Number Type]
- "selected_real_kind in Fortran Wiki". fortranwiki.org.
- "The GNU C Library: Complex Numbers". gnu.org.
- (2016-06-17). "Grammar vb".
- "for...of". mozilla.org.
- "Try-Catch for VB". google.com.
- "The Rust Programming Language".
- "Prime decomposition – Rosetta Code". rosettacode.org.
- "iso_fortran_env in Fortran Wiki". fortranwiki.org.
- "Execute a system command – Rosetta Code". rosettacode.org.
- "EXECUTE_COMMAND_LINE – The GNU Fortran Compiler". gnu.org.
This article was imported from Wikipedia and is available under the Creative Commons Attribution-ShareAlike 4.0 License. Content has been adapted to SurfDoc format. Original contributors can be found on the article history page.
Ask Mako anything about Comparison of programming languages (basic instructions) — get instant answers, deeper analysis, and related topics.
Research with MakoFree with your Surf account
Create a free account to save articles, ask Mako questions, and organize your research.
Sign up freeThis content may have been generated or modified by AI. CloudSurf Software LLC is not responsible for the accuracy, completeness, or reliability of AI-generated content. Always verify important information from primary sources.
Report