Comparison of programming languages (basic instructions): Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
→‎Array declaration: finishing what User:Mike92591 started
Line 426: Line 426:
|-
|-
| C++ (STL)
| C++ (STL)
| type '''x['''size'''];''' or<br /> '''[[std::vector|«std::»vector]]<'''type'''> x(n);'''
| type '''x['''size'''];''' or<br /> '''[[std::vector|«std::»vector]]<'''type'''> x('''size''');'''
|-
|-
| C#
| C#
| type'''[] x = new '''type'''[n];
| type'''[] x = new '''type'''['''size'''];
| type'''[,,'''...'''] x = new '''type'''[n1,n2,'''...'''];'''
| type'''[,,'''...'''] x = new '''type'''['''size1''','''size2''','''...'''];'''
|-
|-
| Java
| Java
| type'''[] x = new '''type'''[n];'''<ref name="jarray">The C-like "type '''x[]'''" works in Java, however "type'''[] x'''" is the preferred form of array declaration.</ref>
| type'''[] x = new '''type'''['''size'''];'''<ref name="jarray">The C-like "type '''x[]'''" works in Java, however "type'''[] x'''" is the preferred form of array declaration.</ref>
| type'''[][]'''...''' x = new '''type'''[n1][n2]'''...''';'''<ref name="jarray" /><ref name="arrayofarray">Multidimensional arrays in this language are actually arrays of arrays ([[Iliffe vector]]). i.e. arrays of references to subarrays.</ref>
| type'''[][]'''...''' x = new '''type'''['''size1''']['''size2''']'''...''';'''<ref name="jarray" /><ref name="arrayofarray">Multidimensional arrays in this language are actually arrays of arrays ([[Iliffe vector]]). i.e. arrays of references to subarrays.</ref>
|-
|-
| JavaScript
| JavaScript
Line 444: Line 444:
|-
|-
| Common Lisp
| Common Lisp
| '''(setf x (make-array n))'''
| '''(setf x (make-array '''size'''))'''
| '''(setf x (make-array '(n1 n2 '''...''')))'''
| '''(setf x (make-array '('''size1''' '''size2''' '''...''')))'''
|-
|-
| Scheme
| Scheme
| '''(define x (make-vector n))'''
| '''(define x (make-vector '''size'''))'''
|
|
|-
|-
Line 458: Line 458:
|-
|-
| Visual Basic
| Visual Basic
| rowspan=2| '''Dim x(n) As '''type'''
| rowspan=2| '''Dim x('''size''') As '''type'''
| rowspan=2| '''Dim x(n1, n2,...) As '''type'''
| rowspan=2| '''Dim x('''size1''', '''size2''',...) As '''type'''
|-
|-
| Visual Basic .NET
| Visual Basic .NET
Line 468: Line 468:
|-
|-
| S-Lang
| S-Lang
| '''x = '''type'''[n];'''
| '''x = '''type'''['''size'''];'''
| '''x = '''type'''[n1, n2, '''...'''];'''
| '''x = '''type'''['''size1''', '''size2''', '''...'''];'''
|-
|-
| FORTRAN 77
| FORTRAN 77
| type '''X(N)'''
| type '''X('''size''')'''
| type '''X(N1, N2,'''...''')'''
| type '''X('''size1''', '''size2''','''...''')'''
|-
|-
| PHP
| PHP
Line 484: Line 484:
|-
|-
| Ruby
| Ruby
| '''x = Array.new(n)'''
| '''x = Array.new('''size''')'''
|
|
|-
|-
| Windows PowerShell
| Windows PowerShell
| '''$x = New-Object ''''type'''[]' n;''' or<br /> «'''['''type'''[]]'''»'''$x = @()'''
| '''$x = New-Object ''''type'''[]' '''size''';''' or<br /> «'''['''type'''[]]'''»'''$x = @()'''
| '''$x = New-Object ''''type'''[,,'''...''']' n1,n2,...;''' or<br /> «'''['''type'''[,,'''...''']]'''»'''$x = @(@(), @(), @(), '''...''')'''
| '''$x = New-Object ''''type'''[,,'''...''']' '''size1''','''size2''',...;''' or<br /> «'''['''type'''[,,'''...''']]'''»'''$x = @(@(), @(), @(), '''...''')'''
|-
|-
| OCaml
| OCaml
| '''let x = Array.make '''n initval
| '''let x = Array.make '''size initval
|
|
|-
|-
| Haskell (GHC)
| Haskell (GHC)
| '''x = Array.array (0, '''n'''-1)''' list_of_association_pairs
| '''x = Array.array (0, '''size'''-1)''' list_of_association_pairs
| '''x = Array.array ((0, 0,'''...'''), ('''n1'''-1, '''n2'''-1,'''...'''))''' list_of_association_pairs
| '''x = Array.array ((0, 0,'''...'''), ('''size1'''-1, '''size2'''-1,'''...'''))''' list_of_association_pairs
|}
|}



Revision as of 13:28, 4 September 2008

Comparison of programming languages is a common topic of discussion among software engineers. Basic instructions of several programming languages are compared here.

Variable declaration

How to declare variable x as the following types:

Integers

8 bit (byte) 16 bit (short integer) 32 bit 64 bit (long integer) Arbitrarily precise (bignum)
Signed Unsigned Signed Unsigned Signed Unsigned Signed Unsigned
C (C99) int8_t x; or
signed char x;
uint8_t x; or
unsigned char x;
int16_t x; or
short x;*[1]
uint16_t x; or
unsigned short x;*[1]
int32_t x; or
long x;* or
int x;*[1]
uint32_t x; or
unsigned long x;* or
unsigned int x;*[1]
int64_t x; or
long long x;*[1]
uint64_t x; or
unsigned long long x;*[1]
[2]
C++ (STL) signed char x; unsigned char x; short x;*[1] unsigned short x;*[1] long x;* or
int x;*[1]
unsigned long x;* or
unsigned int x;*[1]
[2] [2]
C# sbyte x; byte x; short x; ushort x; int x; uint x; long x; ulong x;
Java byte x; [2] char x;[3] [2] [2] java.math.BigInteger x;
Common Lisp [4] (setf x value)
Scheme[4] (define x value)
Pascal (Free Pascal) var x: shortint; var x: byte; var x: smallint; or
var x: integer;
var x: word; var x: longint; var x: longword; var x: int64; var x: qword; [2]
Visual Basic [2] Dim x As Byte Dim x As Integer [2] Dim x As Long [2]
Visual Basic .NET Dim x As SByte Dim x As Short Dim x As UShort Dim x As Integer Dim x As UInteger Dim x As Long Dim x As ULong
Python [4] [2] x = value [2] x = value
JavaScript [4] [2]
S-Lang [4] x = value;
FORTRAN 77 [2] INTEGER X [2]
PHP [4] $x = value;[5] [2] $x = value;[5] [2] $x = value;[5] [2] $x = value;[5] [2] $x = string; (BCMath) or

$x = gmp_init(value); (GMP)

Perl [4] $x = value; use Math::BigInt; $x = Math::BigInt->new(string);
Ruby [4] x = value
Windows PowerShell $x = value; or
New-Variable -Name x -Value value -Description description
OCaml[6][7] [2] let x «: int32» = value or
let x «: int» = value*[8]
[2] let x «: int64» = value [2] open Big_int;; let x «: big_int» = value
Haskell (GHC)[6][7] import Int
«x :: Int8»
x = value
import Word
«x :: Word8»
x = value
import Int
«x :: Int16»
x = value
import Word
«x :: Word16»
x = value
import Int
«x :: Int32»
x = value or
«x :: Int»
x = value[9]
import Word
«x :: Word32»
x = value or
«x :: Word»
x = value[10]
import Int
«x :: Int64»
x = value
import Word
«x :: Word64»
x = value
«x :: Integer»
x = value

Floating point

Single precision Double precision
C (C99) float x; double x;
C++ (STL)
C#
Java
Common Lisp[4] (setf x value)
Scheme[4] (define x value)
Pascal (Free Pascal) var x: real; var x: extended;
Visual Basic Dim x As Single Dim x As Double
Visual Basic .NET
Python[4] [2] x = value
JavaScript[4] [2] var x = value; or
var x = new Number (value); [11]
S-Lang[4] x = valuef; x = value;
FORTRAN 77 REAL X DOUBLE PRECISION X
PHP[4] $x = value;
Perl[4]
Ruby x = value
Windows PowerShell $x = value; or
New-Variable -Name x -Value value -Description description
OCaml[6][7] [2] let x «: float» = value
Haskell (GHC)[6][7] «x :: Float»
x = value
«x :: Double»
x = value

Complex numbers

Integer Floating point
C (C99) [2] type complex x;
C++ (STL) «std::»complex<type> x;
C# [2]
Java
Common Lisp (setf x #C(re im)) or
(setf x (complex re im))
Scheme (define x re+imi)
Pascal
Visual Basic [2]
Visual Basic .NET
Perl use Math::Complex;
...
$x = re + im*i; or
$x = cplx(re, im);
Python x = re + imj or
x = complex(re, im)
JavaScript [2]
S-Lang [2] x = re + imi; or
x = re + imj;
FORTRAN 77 COMPLEX X
Ruby
Windows PowerShell [2]
OCaml[6] [2] open Complex;; let x = { re = re; im = im }
Haskell (GHC)[6] import Complex
x = re :+ im

Other variable types

Text Boolean Object/Universal
Character String
C (C99) char x; char x[length]; or
char *x;
bool x;[12] void *x;
C++ (STL) «std::»string x;
C# string x; bool x; object x;
Java String x; boolean x; Object x;
Common Lisp[4] (setf x #\character) (setf x "string") (setf x value)
Scheme[4] (define x #\character) (define x "string") (define x value)
Pascal var x: char; var x: string; var x: boolean; [2]
Visual Basic [2] Dim x As String Dim x As Boolean Dim x As Variant
Visual Basic .NET Dim x As Char Dim x As Object
Python[4] x = value x = "string" or
x = 'string'
x = value
JavaScript[4] var x = value; var x = "string"; or
var x = new String("value");
var x = value; or
var x = new Boolean (value);
var x = new Object (); or
var x = {}; or
var x = {property1: value1, property2: value2, ... };
S-Lang[4] x = value; x = "string"; x = value; [12]
FORTRAN 77 CHARACTER*1 X CHARACTER*length X LOGICAL X [2]
PHP[4] $x = value; $x = "string"; or
$x = 'string';
$x = value;
Perl[4]
Ruby x = value x = "string" x = value
Windows PowerShell $x = [char]UnicodeCharacterCode; or
$x = [char]"character"; or
$x = [char]'character'; or
$x = "character"[0]; or
$x = 'character'[0]
$x = "string"; or
$x = 'string'
$x = value
OCaml[6][7] let x «: char» = value let x «: string» = value let x «: bool» = value let x = value
Haskell (GHC)[6][7] «x :: Char»
x = value
«x :: String»
x = value
«x :: Bool»
x = value
[2]

Array declaration

How to declare x as an array whose components do not have any particular defined values (where array dimensions can be explicitly defined) :

one-dimensional array multi-dimensional array
C (C99) type x[size]; type x[size1][size2]...;
C++ (STL) type x[size]; or
«std::»vector<type> x(size);
C# type[] x = new type[size]; type[,,...] x = new type[size1,size2,...];
Java type[] x = new type[size];[13] type[][]... x = new type[size1][size2]...;[13][14]
JavaScript var x = new Array («size»); or

var x = new Array (elements); or
var x = [«elements»];

var x = new Array (array1, array2, ...); or

var x = [array1, array2,...];[14]

Common Lisp (setf x (make-array size)) (setf x (make-array '(size1 size2 ...)))
Scheme (define x (make-vector size))
Pascal var x: array[first..last] of type;[15] var x: array[first1..last1] of array[first2..last2] ... of type; [15]

or
var x: array[first1..last1, first2..last2, ...] of type; [15]

Visual Basic Dim x(size) As type Dim x(size1, size2,...) As type
Visual Basic .NET
Python x = [] x = , [], [], ...][14]
S-Lang x = type[size]; x = type[size1, size2, ...];
FORTRAN 77 type X(size) type X(size1, size2,...)
PHP $x = array(elements); $x = array(array(elements), array(elements), ...);[14]
Perl @x = (elements); or
$ref = [elements];
@x = ([elements], [elements], ...);
Ruby x = Array.new(size)
Windows PowerShell $x = New-Object 'type[]' size; or
«[type[]]»$x = @()
$x = New-Object 'type[,,...]' size1,size2,...; or
«[type[,,...]]»$x = @(@(), @(), @(), ...)
OCaml let x = Array.make size initval
Haskell (GHC) x = Array.array (0, size-1) list_of_association_pairs x = Array.array ((0, 0,...), (size1-1, size2-1,...)) list_of_association_pairs

Control flow

Statements in guillemets (« … ») are optional.

Conditional statements

if else if select case
C (C99) if (condition) {instructions} «else {instructions}» if (condition) {instructions} else if (condition) {instructions} ... «else {instructions}» switch (variable) {case case1: instructions «break;» ... «default: instructions»}
C++ (STL)
Java
JavaScript
PHP
C# switch (variable) {case case1: instructions; jump statement;... «default: instructions; jump statement;»}
Windows PowerShell if (condition) { instructions } elseif (condition) { instructions } ... «else { instructions }» switch (variable) {case1 { instructions «break;» } ... «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 }»}
Ruby if condition
instructions
«else
instructions»
end
if condition
instructions
elsif condition
instructions
...
«else
instructions»
end
case variable
when
case1 then
instructions
...
«else instructions»
end
Common Lisp (when condition instructions) or
(if condition (progn instructions) «(progn instructions)»)
(cond (condition1 instructions) (condition2 instructions) ... «(t instructions)») (case (variable) (case1 instructions) (case2 instructions) ... «(t instructions)»)
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)»)
Pascal 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
»;
case variable of
case1: instructions;
...
«else: instructions »
end;
Visual Basic If condition Then
instructions
«Else
instructions»
End If
If condition Then
instructions
ElseIf condition Then
instructions
...
«Else
instructions»
End If
Select Case variable
Case case1
instructions
...
«Case Else
instructions»
End Select
Visual Basic .NET
Python if condition :
Tab instructions
«else:
Tab ↹ instructions»
if condition :
Tab ↹ instructions
elif condition :
Tab ↹ instructions
...
«else:
Tab ↹ instructions»
[2]
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 77 IF condition THEN
instructions
«ELSE
instructions»
ENDIF
IF condition THEN
instructions
ELSEIF
condition THEN
instructions
...
«ELSE
instructions»
ENDIF
     index = f(variable)
     GOTO ( c1, c2, ... cn) index
...
c1  instructions
OCaml if condition then expression «else expression» or
if condition then begin instructions end «else begin instructions end»
if condition then expression else if condition then expression ... «else expression» or
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»[16]
Haskell (GHC) if condition then expression else expression or
when condition (do instructions) or
unless notcondition (do instructions)
if condition then expression else if condition then expression ... else expression case value of {pattern1 -> expression; pattern2 -> expression ... «; _ -> expression»}[16]
if else if select case

Loop statements

The bold is the literal code. The non-bold is interpreted by the reader. Statements in guillemets (« … ») are optional.

while do while for i = 1 to N foreach
C (C99) while (condition) { instructions } do { instructions } while (condition) for («type» i = 0; i < N; i++) { instructions } [2]
C++ (STL) «std::»for_each(start, end, function)
C# foreach (type item in set) { instructions }
Java for (type item : set) { instructions }
JavaScript for (i = 0; i < N; i++) { instructions } for ( property in object) { instructions }
PHP for ($i = 0; $i < N; $i++) { instructions } foreach (set as item) { instructions }
or
foreach (set as key => item) { instructions }
Windows PowerShell for ($i = 0; $i -lt N; $i++) { instructions } foreach (item in set) { instructions using item }
Perl while (condition) { instructions } or
until (notcondition) { instructions }[17]
do { instructions } while (condition) or
do { instructions } until (notcondition)[17]
for ($i = 0; $i < N; $i++) { instructions } or
for«each» «$i» (0 .. N-1) { instructions }
for«each» «$item» (set) { instructions }
Ruby while condition
instructions
end
or
until notcondition
instructions
end [17]
begin
instructions
end while condition
or
begin
instructions
end until notcondition [17]
1.upto(n) { |i| instructions } or
0.step(n - 1, 1) { |i| instructions }
set.each { |item| instructions }
Common Lisp (do () (notcondition) instructions)[17] (dotimes (i N) instructions) or
(do ((i 0 (1+ i))) ((>= i N)) instructions)
(dolist (item set) instructions)
Scheme (do () (notcondition) instructions)[17] or
(let loop () (if condition (begin instructions (loop))))
(let loop () (instructions (if condition (loop)))) (do ((i 0 (+ i 1))) ((>= i N)) instructions) or
(let loop ((i 0)) (if (< i N) (begin instructions (loop (+ i 1)))))
(for-each (lambda (item) instructions) list)
Pascal while condition do begin
instructions
end
repeat
instructions
until notcondition;[17]
for i := 1 «step 1» to N do begin
instructions
end;[18]
[2]
Visual Basic Do While condition
instructions
Loop
or
Do Until notcondition
instructions
Loop [17]
Do
instructions
Loop While condition
or
Do
instructions
Loop Until notcondition [17]
For i = 1 To N «Step 1»
instructions
Next i
[2]
Visual Basic .NET For i «As type» = 1 To N «Step 1»
instructions
Next i[18]
For Each item As type In set
instructions
Next item
Python while condition :
Tab ↹ instructions
«else:
Tab ↹ instructions»
[2] for i in range(0, N):
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 = 0; i < N; i++) { instructions } «then optional-block» foreach item(set) «using (what)» { instructions } «then optional-block»
FORTRAN 77 [2] DO nnnn I = 1,N
instructions
nnnn CONTINUE
[2]
OCaml while condition do instructions done [2] for i = 0 to N-1 do instructions done Array.iter (fun item -> instructions) array
List.iter (fun item -> instructions) list
Haskell (GHC) [2] Control.Monad.forM_ [0..N-1] (\i -> do instructions) Control.Monad.forM_ list (\item -> do instructions)

Exceptions

The bold is the literal code. The non-bold is interpreted by the reader. Statements in guillemets (« … ») are optional.

throw handler assertion
C (C99) longjmp(state, exception); switch (setjmp(state)) { case 0: instructions break; case exception: instructions ... } assert(condition);
C++ (STL) throw exception; try { instructions } catch «(exception)» { instructions } ...
C# try { instructions } catch «(exception)» { instructions } ... «finally { instructions }» Debug.Assert(condition);
Java assert condition;
JavaScript try { instructions } catch (exception) { instructions } «finally { instructions }» ?
PHP try { instructions } catch (exception) { instructions } ... assert(condition);
S-Lang try { instructions } catch «exception» { instructions } ... «finally { instructions }» ?
Windows PowerShell trap «[exception]» { instructions } ... instructions ?
Perl die exception; eval { instructions }; if ($@) { instructions } ?
Ruby raise exception begin
instructions
rescue
exception
instructions
...
«else
instructions»
«ensure
instructions»
end
Common Lisp (error exception) (handler-case (progn instructions) (exception instructions) ...) ?
Scheme (R6RS) (raise exception) (guard (con (condition instructions) ...) instructions) ?
Pascal raise Exception.Create() try Except on E: exception do begin instructions end; end; ?
Visual Basic [2] [2] ?
Visual Basic .NET Throw exception Try
instructions
Catch «exception» «When condition»
instructions
...
«Finally
instructions»
End Try
Debug.Assert(condition)
Python raise exception try:
Tab ↹ instructions
except «exception»:
Tab ↹ instructions
...
«else:
Tab ↹ instructions»
«finally:
Tab ↹ instructions»
assert condition
FORTRAN 77 [2] [2] ?
OCaml raise exception try expression with pattern -> expression ... assert condition
Haskell (GHC) throw exception
or
throwError expression
catch tryExpression catchExpression
or
catchError tryExpression catchExpression
assert condition expression

Other control flow statements

exit block(break) continue label branch (goto) return value from generator
C (C99) break; continue; label: goto label; [2]
C++ (STL)
C# yield return value;
Java break «label»; continue «label»; [2]
JavaScript
PHP break «levels»; continue «levels»; [2]
Perl last «label»; next «label»; label: goto label;
Common Lisp
Scheme
Pascal break; continue; [2]
Visual Basic Exit block [2] GoTo label
Visual Basic .NET Continue block
Python break continue [2] yield value
S-Lang break; continue;
FORTRAN 77 [2] a number in columns 1 to 5 GOTO label [2]
Ruby break next
Windows PowerShell break« label» continue
OCaml [2]
Haskell (GHC) [2]

Function declaration

Statements in guillemets (« … ») are optional. See reflection for calling and declaring functions by strings.

basic/void function value-returning function required main function
C (C99) void foo(«parameters») { instructions } type foo(«parameters») { instructions ... return value; } int main() { instructions } or
int main(int argc, char *argv[]) { instructions }
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 }
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; } [2]
Common Lisp [2] (defun foo (parameters) instructions) [2]
Scheme (define (foo parameters) instructions) or
(define foo (lambda (parameters) instructions))
Pascal procedure foo(«parameters»); «forward;»[19]
begin
instructions end;
function foo(«parameters»): return's type;
begin
... foo := value; ... end;
begin instructions end.
Visual Basic Sub Foo(«parameters»)
instructions
End Sub
Function Foo(«parameters») As type
instructions
...
Foo = value
...
End Function
Sub Main()
instructions
End Sub
Visual Basic .NET Function Foo(«parameters») As type
instructions
...
Return value
End Function
Sub Main(«ByVal CmdArgs() As String»)
instructions
End Sub

or
Function Main(«ByVal CmdArgs() As String») As Integer
instructions
End Function
Python[20] def foo(«parameters»):
Tab ↹ instructions
def foo(«parameters»):
Tab ↹ ...
Tab ↹ return value
[2]
S-Lang define foo («parameters« ;qualifiers»») { instructions } define foo («parameters« ;qualifiers»») { instructions ... return value; } public define slsh_main () { instructions }
FORTRAN 77 SUBROUTINE FOO«(parameters)»
instructions
END
type FUNCTION FOO«(parameters)»
...
FOO = value
...
END
PROGRAM main
PHP function foo(«parameters») { instructions } function foo(«parameters») { instructions ... return value; } [2]
Perl sub foo { «my (parameters) = @_;» instructions } sub foo { «my (parameters) = @_;» instructions... «return» value; }
Ruby def foo«(parameters)»
instructions
end
def foo«(parameters)»
instructions
expression resulting in return value
end
or
def foo«(parameters)»
instructions
return value
end
Windows PowerShell 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 [2] let «rec» foo parameters = expression or
let foo = fun parameters -> expression
Haskell foo parameters = expression or
foo parameters = do ... return value
«main :: IO ()»
main = do instructions

Type conversions

string to integer[21] string to long integer[21] string to floating point[21] integer to string[21] floating point to string[21]
C (C99) integer = atoi(string); long = atol(string); float = atof(string); sprintf(string, "%i", integer); sprintf(string, "%f", float);
C++ (STL) «std::»istringstream(string) >> number; «std::»ostringstream o; o << number; string = o.str();
C# integer = int.Parse(string); long = long.Parse(string); float = float.Parse(string); or
double = double.Parse(string);
string = number.ToString();
Java integer = Integer.parseInt(string); long = Long.parseLong(string); float = Float.parseFloat(string); or
double = Double.parseDouble(string);
string = Integer.toString(integer); string = Float.toString(float); or
string = Double.toString(double);
JavaScript integer = parseInt(string); or
integer = new Number(string) or
integer = string*1;
float = parseFloat(string); or
float = new Number (string) or
float = string*1;
string = number.toString (); or
string = new String (number); or
string = number+"";
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))
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 77 READ(string,format) integer [2] READ(string,format) float 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 [22] string = "integer"; or
string = sprintf("%d", integer);
string = "float"; or
string = sprintf("%f", float);
Ruby integer = string.to_i float = string.to_f string = number.to_s
Windows PowerShell integer = [int]string long = [long]string float = [float]string string = [string]number; or
string = "number"; or
string = (number).ToString()
OCaml let integer = int_of_string string let float = float_of_string string let string = string_of_int integer let string = string_of_float float
Haskell (GHC) number = read string string = show number

Standard Input and Standard Output

read from write to
stdin stdout stderr
C (C99) scanf(format, &x); or
fscanf(stdin, format, &x); [23]
printf( format, x); or
fprintf(stdout, format, x); [24]
fprintf(stderr, format, x );[25]
C++ «std::»cin >> x; «std::»cout << x; «std::»cerr << x; or
«std::»clog <<
x;
C# x = Console.Read(); or
x = Console.ReadLine();
Console.Write(«format, »x); or
Console.WriteLine(«format, »x);
Console.Error.Write(«format, »x); or
Console.Error.WriteLine(«format, »x);
Java x = System.in.read(); 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);
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)
Pascal read(x); or
readln(x);
write(x); or
writeln(x);
[2]
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)
Python x = raw_input(«prompt») print x or
sys.stdout.write(x)
print >>sys.stderr, x or
sys.stderr.write(x)
S-Lang fgets (&x, stdin) fputs (x, stdout) fputs (x, stderr)
FORTRAN 77 READ(5,format) variable names WRITE(6,format) expressions [2]
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;
Ruby x = gets puts x or
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 s = read_line () or
Scanf.scanf format (fun x ... -> ...)
print_int x or
print_endline s or
Printf.printf format x ...
prerr_int x or
prerr_endline s or
Printf.eprintf format x ...
Haskell (GHC) x = readLn or
x <- getLine
print x or
putStrLn x
hPrint stderr x

Reading command-line arguments

Argument values Argument counts Program name / Script name
C (C99) argv[n] argc first argument
C++
C# args[n] args.Length Assembly.GetEntryAssembly().Location;
Java args.length same as name of class
JavaScript
Windows Script Host implementation
WScript.Arguments(n) WScript.Arguments.length ?
Common Lisp ? ? ?
Scheme (R6RS) (list-ref (command-line) n) (length (command-line)) first argument
Pascal ParamStr(n) ParamCount first argument
Visual Basic Command [2] ?
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 77 [2] ?
PHP $argv[n] $argc first argument
Perl $ARGV[n] scalar(@ARGV) $0
Ruby ARGV[n] ARGV.size $0
Windows PowerShell $args[n] $args.Length $MyInvocation.MyCommand.Name
OCaml Sys.argv.(n) Array.length Sys.argv first argument
Haskell (GHC) System.getArgs !! n length System.getArgs System.getProgName

Execution of commands

Shell command Execute program
C system(command); execl(path, args); or
execv(path, arglist);
C++
C# System.Diagnostics.Process.Start(path, argstring);
Visual Basic Interaction.Shell(command «WindowStyle» «isWaitOnReturn»)
Visual Basic .NET Microsoft.VisualBasic.Interaction.Shell(command «WindowStyle» «isWaitOnReturn») or
System.Diagnostics.Process.Start(path, argstring)
Java Runtime.exec(command); or
new ProcessBuilder(command).start();
JavaScript
Windows Script Host implementation
WScript.CreateObject ("WScript.Shell").Run(command «WindowStyle» «isWaitOnReturn»);
Common Lisp (shell command)
Scheme (system command)
OCaml Sys.command command
Haskell (GHC) System.system command
Perl system(command) or
$output = `command`
exec(path, args)
Python os.system(command) subprocess.Popen(command) or
os.execv(path, args)
S-Lang system(command)
Windows PowerShell [Diagnostics.Process]::Start(command) «Invoke-Item »program arg1 arg2 …

Notes

  1. ^ a b c d e f g h i j The C and C++ languages do not specify the exact width of the integer types "short", "int", "long", and (C99) "long long", so they are implementation-dependent and typical values are here marked with asterisk. The "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 also defines the "[u]intN_t" exact-width types in the stdint.h header. See C syntax#Integral types for more information.
  2. ^ a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac ad ae af ag ah ai aj ak al am an ao ap aq ar as at au av aw ax ay az ba bb bc bd be bf bg bh bi bj bk bl bm bn bo bp bq br This language does not support this feature.
  3. ^ Commonly used for characters.
  4. ^ a b c d e f g h i j k l m n o p q r s t u v In this language, types are dynamic. Type checking is done on the actual object at runtime.
  5. ^ a b c d The size of PHP's integer type is platform-dependent
  6. ^ a b c d e f g h Variables cannot be assigned to in this language, making them effectively constants.
  7. ^ a b c d e f Types in this language are automatically inferred and checked at compile time. Type annotations as given here are completely optional.
  8. ^ Technically, "int" values in OCaml are only 31 bits wide. For most purposes, however, "int" can be used where 32-bit integers are used, and it is more efficient.
  9. ^ Technically, "Int" values in Haskell are only guaranteed to be at least 30 bits wide. For most purposes, however, "Int" can be used where 32-bit integers are used, and it is more efficient.
  10. ^ Technically, "Word" values in Haskell are only guaranteed to be at least 30 bits wide. For most purposes, however, "Word" can be used where 32-bit integers are used, and it is more efficient.
  11. ^ 8.5 The Number Type [1]
  12. ^ a b This language represents boolean true as a non-zero valued integer, and boolean false as an integer whose value is zero.
  13. ^ a b The C-like "type x[]" works in Java, however "type[] x" is the preferred form of array declaration.
  14. ^ a b c d Multidimensional arrays in this language are actually arrays of arrays (Iliffe vector). i.e. arrays of references to subarrays.
  15. ^ a b c Subranges are use to define the bounds of the array
  16. ^ a b This syntax performs pattern matching and is very powerful. It is usually used to deconstruct algebraic data types.
  17. ^ a b c d e f g h i The instructions are repeated while the condition is false
  18. ^ a b "step n" is used to change the loop interval. If "step" is omitted, then the loop interval is 1.
  19. ^ Pascal requires "forward;" for forward declaration.
  20. ^ Python also supports decorators on functions which transparently wrap the function as given with another function
  21. ^ a b c d e Where string is a signed decimal number
  22. ^ Perl doesn't have separate types. Strings and numbers are interchangeable.
  23. ^ gets(x) and fgets(x, length, stdin) read unformatted text from stdin. Use of gets is not recommended
  24. ^ puts(x) and fputs(x, stdout) write unformatted text to stdout
  25. ^ fputs(x, stderr) writes unformatted text to stderr