Comparison of programming languages (basic instructions): Difference between revisions
Wiki Tesis (talk | contribs) |
→Conditional statements: +bash shell |
||
Line 1,665: | Line 1,665: | ||
|- |
|- |
||
| Haskell (GHC) |
| Haskell (GHC) |
||
| <tt>'''if''' condition '''then''' expression '''else''' expression |
| <tt>'''if''' condition '''then''' expression '''else''' expression</tt><br/>or<br/><tt>'''when''' condition '''(do''' instructions''')'''</tt><br/>or<br/><tt>'''unless''' notcondition '''(do''' instructions''')'''</tt> |
||
| <tt>result '''<nowiki>|</nowiki>''' condition '''=''' expression <ul>'''<nowiki>|</nowiki>''' condition '''=''' expression <br/>'''<nowiki>|</nowiki> otherwise =''' expression</ul></tt> |
| <tt>result '''<nowiki>|</nowiki>''' condition '''=''' expression <ul>'''<nowiki>|</nowiki>''' condition '''=''' expression <br/>'''<nowiki>|</nowiki> otherwise =''' expression</ul></tt> |
||
| <tt>'''case''' value '''of {<ul>'''pattern1''' -> '''expression''';<br/>'''pattern2''' -> '''expression''';'''<br/> ... <br/>«'''_ -> '''expression»</ul>'''}'''{{ref|pattern matching|[b]}}</tt> |
| <tt>'''case''' value '''of {<ul>'''pattern1''' -> '''expression''';<br/>'''pattern2''' -> '''expression''';'''<br/> ... <br/>«'''_ -> '''expression»</ul>'''}'''{{ref|pattern matching|[b]}}</tt> |
||
|- |
|||
| Bash shell |
|||
| <poem><tt>'''if''' condition-command; '''then''' |
|||
{{space|4}}expression |
|||
«'''else''' |
|||
{{space|4}}expression» |
|||
'''fi'''</tt></poem> |
|||
| <poem><tt>'''if''' condition-command; '''then''' |
|||
{{space|4}}expression |
|||
'''elif''' condition-command; '''then''' |
|||
{{space|4}}expression |
|||
«'''else''' |
|||
{{space|4}}expression» |
|||
'''fi'''</tt></poem> |
|||
| <poem><tt>'''case''' "$variable" '''in''' |
|||
"$condition1" ) |
|||
{{space|4}}command... |
|||
;; |
|||
"$condition2" ) |
|||
{{space|4}}command... |
|||
;; |
|||
'''esac'''</tt></poem> |
|||
| {{n/a}} |
|||
|- |
|- |
||
| rowspan=5| CoffeeScript |
| rowspan=5| CoffeeScript |
Revision as of 02:48, 12 September 2013
This article needs additional citations for verification. (February 2009) |
Comparison of programming languages is a common topic of discussion among software engineers. Basic instructions of several programming languages are compared here.
Conventions of this article
The bold is the literal code. The non-bold is interpreted by the reader. Statements in guillemets (« … ») are optional. Tab ↹ indicates a necessary indent.
Type identifiers
8 bit (byte) | 16 bit (short integer) | 32 bit | 64 bit (long integer) | Word size | Arbitrarily precise (bignum) | ||||||
---|---|---|---|---|---|---|---|---|---|---|---|
Signed | Unsigned | Signed | Unsigned | Signed | Unsigned | Signed | Unsigned | Signed | Unsigned | ||
Ada[1] | range -2**7 .. 2**7 - 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' |
— |
ALGOL 68 (variable-width) | short short int[c] | — | short int[c] | — | int[c] | — | long int[c] | — | int[c] | — | long long int [a][g] |
bytes & bits | |||||||||||
C (C99 fixed-width) | int8_t | uint8_t | int16_t | uint16_t | int32_t | uint32_t | int64_t | uint64_t | int | unsigned int | — |
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] | |||
C++ (C++11 variable-width) | |||||||||||
Objective-C | signed char | unsigned char | short[c] | unsigned short[c] | long[c] | unsigned long[c] | long long[c] | unsigned long long[c] | int or NSInteger |
unsigned int or NSUInteger | |
C# | sbyte | byte | short | ushort | int | uint | long | ulong | — | System.Numerics (.NET 4.0) | |
Java | byte | — | char[b] | — | — | java.math | |||||
Go | int8 | uint8 or byte | int16 | uint16 | int32 | uint32 | int64 | uint64 | int | uint | big.Int |
D | byte | ubyte | short | ushort | int | uint | long | ulong | — | — | BigInt |
Common Lisp[2] | 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 (.NET 4.0) | |||
Python 2.x | — | — | — | — | int | — | long | ||||
Python 3.x | — | — | — | — | — | int | |||||
S-Lang | — | — | — | — | — | — | |||||
Fortran | INTEGER |
— | INTEGER |
— | INTEGER |
— | INTEGER |
— | |||
PHP | — | — | int | — | — | — | [e] | ||||
Perl 5 | —[d] | —[d] | —[d] | —[d] | —[d] | Math::BigInt | |||||
Perl 6 | int8 | uint8 | int16 | uint16 | int32 | uint32 | int64 | uint64 | Int | — | |
Ruby | — | — | — | — | Fixnum | — | Bignum | ||||
Scala | Byte | — | Short | Char[l] | Int | — | Long | — | — | — | scala.math.BigInt |
Smalltalk | — | — | — | — | SmallInteger[i] | — | LargeInteger[i] | ||||
Windows PowerShell | — | — | — | — | — | — | |||||
OCaml | — | — | int32 | — | int64 | — | int or nativeint |
open Big_int;; 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» Int8 |
«import Word» Word8 |
«import Int» Int16 |
«import Word» Word16 |
«import Int» Int32 |
«import Word» Word32 |
«import Int» Int64 |
«import Word» Word64 |
Int | «import Word» 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 | — |
^a The standard constants int shorts and int lengths can be used to determine how many 'short's and 'long's can be usefully prefixed to 'short int' and 'long int'. The actually size of the 'short int', 'int' and 'long int' is available as 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 often 64 bits wide). C99 and C++11[citation needed] also define the [u]intN_t exact-width types in the stdint.h header. SeeC syntax#Integral types for more information.
^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 run time 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 required 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 bit), Short_Integer (16 bit) and Long_Integer (64 bit) are also commonly predefined, but not required by the Ada standard. Run time 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.
Single precision | Double 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] |
Objective-C | |||
C++ (STL) | |||
C# | float | — | |
Java | |||
Go | float32 | float64 | |
D | float | double | real |
Common Lisp | |||
Scheme | |||
ISLISP | |||
Pascal (Free Pascal) | single | double | real |
Visual Basic | Single | Double | — |
Visual Basic .NET | |||
Python | — | float | |
JavaScript | Number[5] | — | |
S-Lang | |||
Fortran | REAL(KIND = n)[c] | ||
PHP | float | ||
Perl | |||
Perl 6 | num32 | num64 | Num |
Ruby | — | Float | — |
Scala | Float | Double | |
Smalltalk | Float | Double | |
Windows PowerShell | |||
OCaml | — | float | — |
F# | float32 | ||
Standard ML | — | real | |
Haskell (GHC) | Float | Double | |
Eiffel | REAL_32 | REAL_64 | |
COBOL[e] | FLOAT-SHORT | FLOAT-LONG |
^a The standard constants real shorts and real lengths can be used to determine how many 'short's and 'long's can be usefully prefixed to 'short real' and 'long real'. The actually size of the 'short real', 'real' and 'long real' is available as 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[6] intrinsic function.
^d ALGOL 68G's run time 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 COBOL also supports 'FLOAT-EXTENDED'. The types 'FLOAT-BINARY-7', 'FLOAT-BINARY-16' and 'FLOAT-BINARY-34', specify IEEE-754 binary floating point variables, and 'FLOAT-DECIMAL-16' and 'FLOAT-DECIMAL-34' specify IEEE decimal floating point variables.
^f Same size as 'double' on many implementations.
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. & long long compl etc. |
C (C99) [7] | — | 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 | ||||
Scheme | ||||
Pascal | — | — | ||
Visual Basic | — | — | ||
Visual Basic .NET | — | — | System.Numerics.Complex (.Net 4.0) | |
Perl | Math::Complex | |||
Perl 6 | complex64 | complex128 | Complex | |
Python | complex | — | ||
JavaScript | — | — | ||
S-Lang | — | — | ||
Fortran | COMPLEX(KIND = n)[a] | |||
Ruby | Complex | — | Complex | |
Scala | — | — | — | |
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 | — | — | — |
^a The value of "n" is provided by the SELECTED_REAL_KIND[6] intrinsic function.
^b Generic type which can be instantiated with any base floating point type.
Other variable types
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, item2, ... } | object |
Java | String | boolean | Object | ||
Go | rune | string | bool | const (
item2 ... |
interface{} |
D | char | string | bool | enum name {item1, item2, ... } | std.variant.Variant |
Common Lisp | |||||
Scheme | |||||
ISLISP | |||||
Pascal (ISO) | char | — | boolean | (item1, item2, ...) | — |
Object Pascal (Delphi) | string | variant | |||
Visual Basic | — | String | Boolean | Enum name
item2 ... |
Variant |
Visual Basic .NET | Char | Object | |||
Python | —[d] | str | bool | object | |
JavaScript | —[d] | String | Boolean | Object | |
S-Lang | |||||
Fortran | CHARACTER(LEN = *) | CHARACTER(LEN = :), allocatable | LOGICAL(KIND = n)[f] | CLASS(*) | |
PHP | —[d] | string | bool | object | |
Perl | —[d] | ||||
Perl 6 | Char | Str | Bool | enum name <item1 item2 ...> or enum name <<:item1(value) :item2(value) ...>> |
Mu |
Ruby | —[d] | String | Object[c] | Object | |
Scala | Char | String | Boolean | object name extends Enumeration {
|
Any |
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 |
^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
fixed size array | dynamic size array | |||
---|---|---|---|---|
one-dimensional array | multi-dimensional array | one-dimensional array | multi-dimensional 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] or simply: [size] |
[first1:last1, first2:last2] or [first1:last1][first2:last2] etc. |
flex[first:last] or simply: flex[size] |
flex[first1:last1, first2:last2] or flex[first1:last1] |
C (C99) | [a] | [a] | ||
C++ (STL) | «std::»array<type, size>(C++11) | «std::»vector<type> | ||
C# | type[] | type[,,...] | System or System |
|
Java | type[][b] | type[][]...[b] | ArrayList or ArrayList<type> | |
D | type[size] | type[size1][size2] | type[] | |
Go | [size]type | [size1][size2]...type | vector.Vector | |
Objective-C | NSArray | NSMutableArray | ||
JavaScript | — | — | Array[d] | |
Common Lisp | ||||
Scheme | ||||
ISLISP | ||||
Pascal | array[first..last] of type[c] | array[first1..last1] of array[first2..last2] ... of type [c] or |
— | — |
Object Pascal (Delphi) | array of type | array of array ... of type | ||
Visual Basic | ||||
Visual Basic .NET | System or System |
|||
Python | list | |||
S-Lang | ||||
Fortran | type :: name(size) | type :: name(size1, size2,...) | type, ALLOCATABLE :: name(:) | type, ALLOCATABLE :: name(:,:,...) |
PHP | array | |||
Perl | ||||
Perl 6 | Array[type] or Array of type | |||
Ruby | Array | |||
Scala | Array[type] | Array[...[Array[type]]...] | ArrayBuffer[type] | |
Smalltalk | Array | OrderedCollection | ||
Windows PowerShell | type[] | type[,,...] | ||
OCaml | type array | type array ... array | ||
F# | type [] or type array | type [,,...] | System or System |
|
Standard ML | type vector or type array | |||
Haskell (GHC) |
^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. Also C's arrays can not be described in this format. See C syntax#Arrays.
^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.
Other types
Simple composite types | Algebraic data types | Unions | ||
---|---|---|---|---|
Records | Tuple expression | |||
Ada[1] | type identifier is «abstract» «tagged» «limited» [record
end record | null record] |
— | Any combination of records, unions and enumerations (as well as references to those, enabling recursive types). | type identifier (variation : discrete_type) is 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;...} | — | ||
Java | —[a] | |||
JavaScript | — | |||
D | struct name {type name;...} | std.variant.Algebraic!(type,...) | union {type name;...} | |
Go | struct {
... |
|||
Common Lisp | (cons val1 val2)[c] | |||
Scheme | — | |||
ISLISP | ||||
Pascal | record
... |
— | — | record
value: (types); ... |
Visual Basic | ||||
Visual Basic .NET | Structure name
... |
|||
Python | —[a] | «(»val1, val2, val3, ... «)» | — | |
S-Lang | struct {name [=value], ...} | |||
Fortran | TYPE name
... |
|||
PHP | —[a] | |||
Perl | —[d] | — | ||
Perl 6 | —[a] | |||
Ruby | OpenStruct.new({:name => value}) | |||
Scala | (val1, val2, val3, ... ) | abstract class name case class Foo(«parameters») extends name |
||
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» | ... |
^a Only classes are supported.
^b struct
s 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
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 name «= initial_value»; or var name = value; |
const type name = value; or readonly type 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»; | const name = value; | |
Go | var name type «= initial_value» or name := initial_value |
const name «type» = initial_value | type synonym type |
Common Lisp | (defparameter name initial_value) or (defvar name initial_value) or (setf (symbol-value 'symbol) 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 | Const name As type = value | |
Visual Basic .NET | Dim name As type«= initial_value» | Imports synonym = type | |
Python | name = initial_value | — | synonym = type[b] |
CoffeeScript | — | ||
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; | |
Perl 6 | «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 | ||
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::type;» name = value | type Synonym = type | |
Forth | VARIABLE name (in some systems use value VARIABLE name instead) | value CONSTANT name |
^a Pascal has declaration blocks. See Comparison of programming languages (basic instructions)#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.
Conditional statements
if | else if | select case | conditional expression | |
---|---|---|---|---|
Ada[1] | if condition then
|
if condition1 then
«else
|
case expression is
|
(if condition1 then
else
(case expression is
|
Seed7 | case expression of when set1 : statements ... «otherwise: statements» end case |
|||
Modula-2 | if condition then
|
if condition1 then
«else
|
case expression of caseLabelList : statements | ... «else statements» end |
|
ALGOL 68 & "brief form" | 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 )
|
( condition | statements «| statements» )
|
( condition | statements |: condition | statements )
|
( variable | statements,... «| statements» )
| ||
C (C99) | if (condition) {instructions} «else {instructions}» |
if (condition) {instructions} else if (condition) {instructions} ... «else {instructions}» |
switch (variable) {
... «default: instructions» |
condition ? valueIfTrue : valueIfFalse |
Objective-C | ||||
C++ (STL) | ||||
D | ||||
Java | ||||
JavaScript | ||||
PHP | ||||
C# | switch (variable) {
... «default: instructions; «jump statement;»» | |||
Windows PowerShell | 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 {
... «default: instructions» |
switch variable {
... «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) {
... «default { instructions }» |
condition ? valueIfTrue : valueIfFalse |
Perl 6 | if condition {instructions} «else {instructions}» or unless notcondition {instructions} |
if condition {instructions} elsif condition {instructions} ... «else {instructions} |
given variable {
... «default { instructions }» |
condition ?? valueIfTrue !! valueIfFalse |
Ruby | if condition
|
if condition
«else
|
case variable when case1
«else
|
condition ? valueIfTrue : valueIfFalse |
Scala | if (condition) {instructions} «else {instructions}» |
if (condition) {instructions} else if (condition) {instructions} ... «else {instructions}» |
expression match {
case pattern2 => expression ... «case _ => expression» |
if (condition) valueIfTrue else valueIfFalse |
Smalltalk | condition ifTrue:
|
condition ifTrue: trueBlockifFalse: falseBlock | ||
Common Lisp | (when condition
(unless condition
(if condition
|
(cond (condition1 instructions)
|
(case expression
|
(if condition valueIfTrue valueIfFalse) |
Scheme | (when conditioninstructions) or (if condition (begin instructions) «(begin instructions)») |
(cond (condition1 instructions) (condition2 instructions) ... «(else instructions)») | (case (variable) ((case1) instructions) ((case2) instructions) ... «(else instructions)») | |
ISLISP | (if condition
|
(cond (condition1 instructions)
|
(case expression
|
(if condition valueIfTrue valueIfFalse) |
Pascal | if condition then begin
«else begin
|
if condition then begin
else if condition then begin
... «else begin
|
case variable of
... «else: instructions» | |
Visual Basic | If condition Then
|
If condition Then
«Else
|
Select Case variable Case case1
«Case Else
|
IIf(condition, valueIfTrue, valueIfFalse) |
Visual Basic .NET | If(condition, valueIfTrue, valueIfFalse) | |||
Python [a] | if condition : Tab ↹ instructions «else: Tab ↹ instructions» |
if condition : Tab ↹ instructions elif condition : Tab ↹ instructions ... «else: Tab ↹ instructions» |
— | valueIfTrue if condition else valueIfFalse (Python 2.5+) |
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
|
IF (condition) THEN
ELSE
|
SELECT CASE(variable)
CASE DEFAULT
|
|
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
| pattern2 -> expression ... «| _ -> expression»[b] |
if condition then valueIfTrue else valueIfFalse |
F# | if condition then Tab ↹ instructions «else Tab ↹ instructions» |
if condition then Tab ↹ instructions elif condition then Tab ↹ instructions ... «else Tab ↹ instructions» | ||
Standard ML | if condition then «(»instructions «)» else «(» instructions «)» |
if condition then «(»instructions «)» else if condition then «(» instructions «)» ... else «(» instructions «)» |
case value of
| 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
| otherwise = expression |
case value of {
pattern2 -> expression; ... «_ -> expression» | |
Bash shell | if condition-command; then |
if condition-command; then |
case "$variable" in "$condition2" ) esac |
— |
CoffeeScript | if condition then expression «else expression» | if condition then expression else if condition then expression «else expression» | switch expression
|
All conditions are expresssions |
if condition
|
if condition
| |||
expression if condition | unless condition
|
switch expression
| ||
unless condition
| ||||
expression unless condition | ||||
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 in 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.
while | do while | for i = first to last | foreach | |
---|---|---|---|---|
Ada[1] | while condition loop
|
loop
|
for index in «reverse» [first .. last | discrete_type] loop
|
for item of «reverse» iterator loop
(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 | ||
C (C99) | 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)
(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 } | for (var index in set) { instructions } or for each (var item in set) { instructions } (JS 1.6+, deprecated[8]) or for (var item of set) { instructions } (EcmaScript 6 proposal, supported in Firefox[9]) | ||
PHP | foreach (range(first, last-1) 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 using item } | ||
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 } | |
Perl | while (condition) { instructions } or until (notcondition) { instructions } |
do { instructions } while (condition) or do { instructions } until (notcondition) |
for«each» «$i» (0 .. N-1) { instructions } or for ($i = first; $i <= last; $i++) { instructions } |
for«each» «$item» (set) { instructions } |
Perl 6 | 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
or until notcondition
|
begin
or begin
|
for i in first...last
or first.upto(last-1) { |i| instructions } |
for item in set
or set.each { |item| instructions } |
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 doWhile:
|
first to: last do:
|
collection do:
|
Common Lisp | (loop
(do () (notcondition)
|
(loop
|
(loop
(dotimes (i N)
(do ((i first (1+ i))) ((>= i last))
|
(loop
(dolist (item set)
(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
|
repeat
|
for i := first «step 1» to last do begin
|
— |
Visual Basic | Do While condition
or Do Until notcondition
|
Do
or Do
|
For i = first To last «Step 1»
|
For Each item In set
|
Visual Basic .NET | For i «As type» = first To last «Step 1»
|
For Each item As type In set
| ||
Python | while condition : Tab ↹ instructions «else: Tab ↹ instructions» |
— | for i in range(first, last): 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)
|
DO
IF (condition) EXIT |
DO I = first,last
|
— |
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-1 do instructions done | Array.iter (fun item -> instructions) array List.iter (fun item -> instructions) list |
F# | while condition do Tab ↹ instructions |
— | for i = first to last-1 do Tab ↹ instructions |
for item in set do Tab ↹ instructions or Seq.iter (fun item -> instructions) set |
Standard ML | while condition do ( instructions ) | — | Array.app (fn item => instructions) array app (fn item => instructions) list | |
Haskell (GHC) | — | Control.Monad.forM_ [0..N-1] (\i -> do instructions) | Control.Monad.forM_ list (\item -> do instructions) | |
Eiffel | from
| |||
CoffeeScript | while condition
|
— | for i in [first..last]
|
for item in set
|
expression while condition | ||||
while condition then expression | ||||
until condition
| ||||
expression until condition | for i in [first..last] then expression | for item in set then expression | ||
until condition then expression | expression for i in [first..last] | expression for item in set |
^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 "∃").
throw | handler | assertion | |
---|---|---|---|
Ada[1] | raise exception_name «with string_expression» | begin
|
pragma Assert («Check =>» boolean_expression ««Message =>» string_expression») [function | procedure | entry] with
any_type with Type_Invariant => boolean_expression |
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)» { instructions } ... «finally { instructions }» | Debug.Assert(condition); | |
Java | try { instructions } catch (exception) { instructions } ... «finally { instructions }» | assert condition; | |
JavaScript | try { instructions } catch (exception) { instructions } «finally { instructions }» | ? | |
D | try { instructions } catch (exception) { instructions } ... «finally { instructions }» | assert(condition); | |
PHP | try { instructions } catch (exception) { 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); |
Perl | die exception; | eval { instructions }; if ($@) { instructions } | ? |
Perl 6 | try { instructions CATCH { when exception { instructions } ...}} | ? | |
Ruby | raise exception | begin
«else
|
|
Smalltalk | exception raise | instructionBlock on: exception do: handlerBlock | assert: conditionBlock |
Common Lisp | (error "exception") or (error (make-condition
|
(handler-case
(handler-bind
|
(assert condition) or (assert condition
(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
|
? |
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
'*** 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
|
Debug.Assert condition |
Visual Basic .NET | Throw exception | Try
«Finally
|
Debug.Assert(condition) |
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 |
^a Common Lisp allows with-simple-restart
, restart-case
and restart-bind
to define restarts for use with invoke-restart
. Unhandled conditions may cause the implementation to show a restarts menu to the user before unwinding the stack.
^b Uncaught exceptions are propagated to the innermost dynamically enclosing execution. Exceptions are not propagated across tasks (unless these tasks are currently synchronised in a rendezvous).
Other control flow statements
exit block(break) | 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; ... |
yield(value) |
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»; | |||
Perl 6 | |||||
Go | break «label» | continue «label» | goto label | ||
Common Lisp | (return) or (return-from block) or (loop-finish) |
(tagbody tag
|
(go tag) | ||
Scheme | |||||
ISLISP | (return-from block) | (tagbody tag
|
(go tag) | ||
Pascal(ISO) | — | label:[a] | goto label; | — | |
Pascal(FPC) | break; | continue; | |||
Visual Basic | Exit block | — | label: | GoTo label | |
Visual Basic .NET | Continue block | ||||
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) |
^a Pascal has declaration blocks. See Comparison of programming languages (basic instructions)#Functions.
^b label must be a number between 1 and 99999.
See reflection 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 ); | — |
C (C99) | foo(«parameters») | void foo(«parameters») { instructions } | type foo(«parameters») { instructions ... return value; } | «global declarations» int main(«int argc, char *argv[]») {
|
Objective-C | ||||
C++ (STL) | ||||
C# | static void Main(«string[] args») { instructions } or static int Main(«string[] args») { instructions } | |||
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} | |||
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 } | |
Common Lisp | (foo «parameters») | (defun foo («parameters»)
(setf (symbol-function 'symbol)
|
(defun foo («parameters»)
|
— |
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»)
|
(defun foo («parameters»)
| ||
Pascal | foo«(parameters)» | procedure foo«(parameters)»; «forward;»[a] «label
begin
|
function foo«(parameters)»: type; «forward;»[a] «label
begin
foo := value |
program name; «label
begin
|
Visual Basic | Foo(«parameters») | Sub Foo(«parameters»)
|
Function Foo(«parameters») As type
Foo = value |
Sub Main()
|
Visual Basic .NET | Function Foo(«parameters») As type
Return value |
Sub Main(«ByVal CmdArgs() As String»)
or Function Main(«ByVal CmdArgs() As String») As Integer
| ||
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»)
|
type FUNCTION foo («arguments»)
... foo = value |
PROGRAM main
|
Forth | «parameters» FOO | : FOO « stack effect comment: ( before -- ) »
|
: FOO « stack effect comment: ( before -- after ) »
|
— |
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; } | |
Perl 6 | 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)»
|
def foo«(parameters)»
«return» value | |
Scala | def foo«(parameters)»«: Unit =» { instructions } | def foo«(parameters)»«: type» = { instructions ... «return» value } | def main(args: Array[String]) { instructions } | |
Windows PowerShell | foo« parameters» | function foo «(parameters)» { instructions }; or function foo { «param(parameters)» instructions } |
function foo «(parameters)» { instructions … return value }; or function foo { «param(parameters)» instructions … return value } |
— |
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»)
|
foo («parameters»): type
|
[b] |
CoffeeScript | foo() | foo = -> | foo = -> value | — |
foo parameters | foo = () -> | foo = ( parameters ) -> value |
^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.
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)); orv
|
getf(proxy, ($g$, livar)); or
|
getf(proxy, ($g$, rvar)); or
|
putf(proxy, ($g$, ival)); or
|
putf(proxy, ($g(width, places, exp)$, rval)); or
| |
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 |
string = [NSString stringWithFormat |
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 |
long = long.Parse |
float = float.Parse double = double.Parse |
string = number | |
D | integer = std.conv.to!int |
long = std.conv.to!long |
float = std.conv.to!float double = std.conv.to!double |
string = std.conv.to!string | |
Java | integer = Integer.parseInt |
long = Long.parseLong |
float = Float.parseFloat double = Double.parseDouble |
string = Integer.toString string = String.valueOf |
string = Float.toString string = Double.toString |
JavaScript[a] | integer = parseInt(string); | float = parseFloat(string); or float = new Number (string) or float = Number (string) or float = string*1; |
string = number.toString (); or string = new String (number); or string = String (number); or string = number+""; | ||
Go | integer, error = strconv.Atoi(string) or integer, error = strconv.ParseInt |
long, error = strconv.ParseInt |
float, error = strconv.ParseFloat |
string = strconv.Itoa(integer) or string = strconv.FormatInt string = fmt.Sprint(integer) |
string = strconv.FormatFloat string = fmt.Sprint |
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) or double = CDbl(string) |
string = CStr(number) | |
Visual Basic .NET | |||||
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); or float = (float)string; |
string = "number"; or string = strval(number); or string = (string)number; | ||
Perl[b] | number = 0 + string; | string = "number"; | |||
Perl 6 | number = +string; | string = ~number; | |||
Ruby | integer = string.to_i or integer = Integer(string) |
float = string.to_f or float = Float(string) |
string = number.to_s | ||
Scala | integer = string.toInt | long = string.toLong | float = string.toFloat or double = string.toDouble |
string = number.toString | |
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_ |
let float = float_ |
let string = string_ |
let string = string_ | |
F# | let integer = int string | let integer = int64 string | let float = float string | let string = string number | |
Standard ML | val integer = Int |
val float = Real |
val string = Int |
val string = Real | |
Haskell (GHC) | number = read string | string = show number |
^a JavaScript only uses floating point numbers so there are some technicalities.[5]
^b Perl doesn't have separate types. Strings and numbers are interchangeable.
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] |
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 Console.Error |
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 std.stdio |
Java | x = System.in.read(); or x = new Scanner(System.in) x = new Scanner(System.in) |
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) |
fmt.Println(x) or fmt.Printf(format, x) |
fmt.Fprintln(os.Stderr, x) or fmt.Fprintf(os.Stderr, format, 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); |
— |
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 Console.Error |
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(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[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; |
Perl 6 | $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 |
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 |
^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.[12]
Reading command-line arguments
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() |
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 |
Common Lisp | ? | ? | ? |
Scheme (R6RS) | (list-ref (command-line) n) | (length (command-line)) | first argument |
ISLISP | — | — | — |
Pascal | ParamStr(n) | ParamCount | first argument |
Visual Basic | Command[a] | — | App.Path |
Visual Basic .NET | CmdArgs(n) | CmdArgs.Length | [Assembly].GetEntryAssembly().Location |
Python | sys.argv[n] | len(sys.argv) | first argument |
S-Lang | __argv[n] | __argc | first argument |
Fortran | DO i = 1,argc
|
argc = COMMAND_ARGUMENT_COUNT () | CALL GET_COMMAND_ARGUMENT (0,progname) |
PHP | $argv[n] | $argc | first argument |
Perl | $ARGV[n] | scalar(@ARGV) | $0 |
Perl 6 | @*ARGS[n] | @*ARGS.elems | $PROGRAM_NAME |
Ruby | ARGV[n] | ARGV.size | $0 |
Windows PowerShell | $args[n] | $args.Length | $MyInvocation.MyCommand |
OCaml | Sys.argv.(n) | Array.length Sys.argv | first argument |
F# | args.[n] | args.Length | Assembly.GetEntryAssembly() |
Standard ML | List.nth (CommandLine |
length (CommandLine |
CommandLine.name () |
Haskell (GHC) | do { args <- System.getArgs; return args !! n } | do { args <- System.getArgs; return length args } | System.getProgName |
- ^a The command-line arguments in Visual Basic are not separated. A split function Split(string) is required for separating them.
Execution of commands
Shell command | Execute program | Replace current program with new executed program | |
---|---|---|---|
Ada[1] | Not part of the language standard. Commonly done by compiler provided packages or by interfacing to C or Posix.[13] | ||
C | system("command"); | execl(path, args); or execv(path, arglist); | |
C++ | |||
Objective-C | [NSTask launchedTaskWithLaunchPath:(NSString *)path arguments:(NSArray *)arguments]; | ||
C# | System.Diagnostics |
||
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 |
System.Diagnostics |
|
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 | (shell 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 |
Posix.Process |
Perl | system(command) or $output = `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) |
os.execv(path, args) | |
S-Lang | system(command) | ||
Fortran | CALL SYSTEM (command, status) or status = SYSTEM (command)[a] |
||
Windows PowerShell | [Diagnostics.Process]::Start(command) | «Invoke-Item »program arg1 arg2 … |
^a Compiler-dependent extension.[14]
References
- ^ 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), http://www.ada-auth.org/standards/12rm/RM-Final.pdf
- ^ http://www.lispworks.com/documentation/HyperSpec/Front/index.htm
- ^ http://www.islisp.info/specification.html
- ^ a b http://fortranwiki.org/fortran/show/selected_int_kind
- ^ a b 8.5 The Number Type
- ^ a b http://fortranwiki.org/fortran/show/selected_real_kind
- ^ http://www.gnu.org/software/libc/manual/html_node/Complex-Numbers.html#Complex-Numbers
- ^ https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for_each...in
- ^ https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...of
- ^ https://sites.google.com/site/truetryforvisualbasic/
- ^ example
- ^ http://fortranwiki.org/fortran/show/iso_fortran_env
- ^ http://rosettacode.org/wiki/Execute_a_system_command#Ada
- ^ http://gcc.gnu.org/onlinedocs/gfortran/SYSTEM.html#SYSTEM