Informatika & Komputer    
   
Daftar Isi
(Sebelumnya) Comparison of programming lang ...Comparison of programming lang ... (Berikutnya)

Perbandingan -- programming languages (basic instructions)

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

Contents


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

Integers

8 bit (byte)16 bit (short integer)32 bit64 bit (long integer)Word sizeArbitrarily precise (bignum)
SignedUnsignedSignedUnsignedSignedUnsignedSignedUnsignedSignedUnsigned
ALGOL 68 (variable-width)short short int[c]N/Ashort int[c]N/Aint[c]N/Along int[c]N/Aint[c]N/Along long int [a][g]
bytes & bits
C (C99 fixed-width)int8_tuint8_tint16_tuint16_tint32_tuint32_tint64_tuint64_tintunsigned intN/A
C++ (C++11 fixed-width)
C (C99 variable-width)signed charunsigned charshort[c]unsigned short[c]long[c]unsigned long[c]long long[c]unsigned long long[c]
C++ (C++11 variable-width)
Objective-Csigned charunsigned charshort[c]unsigned short[c]long[c]unsigned long[c]long long[c]unsigned long long[c]int
or
NSInteger
unsigned int
or
NSUInteger
C#sbytebyteshortushortintuintlongulongN/ASystem.Numerics.BigInteger (.NET 4.0)
JavabyteN/Achar[b]N/AN/Ajava.math.BigInteger
Goint8uint8 or byteint16uint16int32uint32int64uint64intuintbig.Int
DbyteubyteshortushortintuintlongulongN/AN/ABigInt
Common Lisp[1]          bignum
Scheme           
ISLISP[2]          bignum
Pascal (FPC)shortintbytesmallintwordlongintlongwordint64qwordintegercardinalN/A
Visual BasicN/AByteIntegerN/ALongN/AN/AN/AN/A
Visual Basic .NETSByteShortUShortIntegerUIntegerLongULongSystem.Numerics.BigInteger (.NET 4.0)
Python 2.xN/AN/AN/AN/AintN/Along
Python 3.xN/AN/AN/AN/AN/Aint
S-LangN/AN/AN/AN/AN/AN/A
FortranINTEGER(KIND = n)[f]N/AINTEGER(KIND = n)[f]N/AINTEGER(KIND = n)[f]N/AINTEGER(KIND = n)[f]N/A   
PHPN/AN/AintN/AN/AN/A[e]
Perl 5N/A[d]N/A[d]N/A[d]N/A[d]N/A[d]Math::BigInt
Perl 6int8uint8int16uint16int32uint32int64uint64IntN/A
RubyN/AN/AN/AN/AFixnumN/ABignum
SmalltalkN/AN/AN/AN/ASmallInteger[i]N/ALargeInteger[i]
Windows PowerShellN/AN/AN/AN/AN/AN/A
OCamlN/AN/Aint32N/Aint64N/Aint
or
nativeint
 open Big_int;
big_int
F#sbytebyteint16uint16int32 or intuint32uint64nativeintunativeintbigint
Standard MLN/AWord8.wordN/AInt32.intWord32.wordInt64.intWord64.wordintwordLargeInt.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
EiffelINTEGER_8NATURAL_8INTEGER_16NATURAL_16INTEGER_32NATURAL_32INTEGER_64NATURAL_64INTEGERNATURALN/A
COBOL[h]BINARY-CHAR SIGNEDBINARY-CHAR UNSIGNEDBINARY-SHORT SIGNEDBINARY-SHORT UNSIGNEDBINARY-LONG SIGNEDBINARY-LONG UNSIGNEDBINARY-DOUBLE SIGNEDBINARY-DOUBLE UNSIGNED  N/A

^a The standard constants int shorts and int lengths can be used to determine how many shorts and longs can be usefully prefixed to short int and long int. The 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. See C 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[3] intrinsic function.
^g ALGOL 68G's run time option --precision "number" can set precision for long long int's 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.

Floating point

Single precisionDouble precisionProcessor dependent
ALGOL 68real[a]long real[a]short real etc. & long long real etc.[d]
Cfloat[b]doubleN/A[b]
Objective-C
C++ (STL)
C#floatN/A
Java
Gofloat32float64
Dfloatdoublereal
Common Lisp   
Scheme   
ISLISP   
Pascal (Free Pascal)singledoublereal
Visual BasicSingleDoubleN/A
Visual Basic .NET
PythonN/Afloat 
JavaScriptNumber[4]N/A
S-Lang   
FortranREAL(KIND = n)[c] 
PHP float 
Perl   
Perl 6num32num64Num
RubyN/AFloatN/A
SmalltalkFloatDouble
Windows PowerShell
OCamlN/AfloatN/A
F#float32
Standard MLN/Areal
Haskell (GHC)FloatDouble 
EiffelREAL_32REAL_64 
COBOL[e]FLOAT-SHORTFLOAT-LONG 

^a The standard constants real shorts and real lengths can be used to determine how many shorts and longs can be usefully prefixed to short real and long real. The 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[5] intrinsic function.
^d ALGOL 68G's run time option --precision "number" can set precision for long long real's 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.

Complex numbers

IntegerSingle precisionDouble precisionHalf and Quadruple precision etc.
ALGOL 68N/Acompllong compl etc.short compl etc. & long long compl etc.
C (C99) [6]N/Afloat complexdouble complexN/A
C++ (STL)N/Astd::complex<float>std::complex<double>
C#N/AN/ASystem.Numerics.Complex
(.Net 4.0)
JavaN/AN/AN/A
GoN/Acomplex64complex128
DN/Acfloatcdouble
Objective-CN/AN/AN/A
Common Lisp   
Scheme   
PascalN/AN/A 
Visual BasicN/AN/A 
Visual Basic .NETN/AN/ASystem.Numerics.Complex
(.Net 4.0)
Perl  Math::Complex 
Perl 6 complex64complex128Complex
Python  complexN/A
JavaScriptN/AN/A 
S-LangN/AN/A 
Fortran COMPLEX(KIND = n)[a]
RubyComplexN/AComplex
SmalltalkComplexComplexComplex
Windows PowerShellN/AN/A 
OCamlN/AN/AComplex.t
F#  System.Numerics.Complex
(.Net 4.0)
Standard MLN/AN/AN/A
Haskell (GHC)N/AComplex.Complex FloatComplex.Complex Double
EiffelN/AN/AN/A

^a The value of "n" is provided by the SELECTED_REAL_KIND[5] intrinsic function.

Other variable types

TextBooleanEnumerationObject/Universal
CharacterString[a]
ALGOL 68charstring & bytesbool & bitsN/A - User definedN/A
C (C99)char
wchar_t
N/Abool[b]enum «name» {item1, item2, ... };void *
C++ (STL)«std::»string
Objective-CunicharNSString *BOOLid
C#charstringboolenum name {item1, item2, ... }object
JavaStringbooleanObject
Gorunestringboolconst (
item1 = iota
item2
...
)
interface{}
Dcharstringboolenum name {item1, item2, ... }std.variant.Variant
Common Lisp     
Scheme     
ISLISP     
Pascal (ISO)charN/Aboolean(item1, item2, ...)N/A
Object Pascal (Delphi)stringvariant
Visual BasicN/AStringBooleanEnum name
item1
item2
...
End Enum
Variant
Visual Basic .NETCharObject
PythonN/A[d]strbool object
JavaScriptN/A[d]StringBoolean Object
S-Lang     
FortranCHARACTER(LEN = *)CHARACTER(LEN = :), allocatableLOGICAL(KIND = n)[f] CLASS(*)
PHPN/A[d]stringbool object
PerlN/A[d]    
Perl 6CharStrBoolenum name <item1 item2 ...> or
enum name <<:item1(value) :item2(value) ...>>
Mu
RubyN/A[d]StringObject[c] Object
Windows PowerShell     
OCamlcharstringboolN/A[e]N/A
F#type name = item1 = value | item2 = value | ...obj
Standard MLN/A[e]N/A
Haskell (GHC)CharStringBoolN/A[e]N/A
EiffelCHARACTERSTRINGBOOLEANN/AANY

^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[3] intrinsic function.

Derived types

Array

fixed size arraydynamic size array
one-dimensional arraymulti-dimensional arrayone-dimensional arraymulti-dimensional array
ALGOL 68[first:last]«modename» or simply: [size]«modename»[first1:last1,first2:last2]«modename» or [first1:last1][first2:last2]«modename» etc.flex[first:last]«modename» or simply: flex[size]«modename»flex[first1:last1,first2:last2]«modename» or flex[first1:last1]flex[first2:last2]«modename» etc.
C (C99)[a][a]  
C++ (STL)«std::»array<type, size>(C++11) «std::»vector<type>
C#type[]type[,,...]System.Collections.ArrayList
or
System.Collections.Generic.List<type>
 
Javatype[][b]type[][]...[b]ArrayList or ArrayList<type> 
Dtype[size]type[size1][size2]type[] 
Go[size]type[size1][size2]...typevector.Vector 
Objective-CNSArray NSMutableArray 
JavaScriptN/AN/AArray[d]
Common Lisp    
Scheme    
ISLISP    
Pascalarray[first..last] of type[c]array[first1..last1] of array[first2..last2] ... of type [c]

or
array[first1..last1, first2..last2, ...] of type [c]

N/AN/A
Object Pascal (Delphi)array of typearray of array ... of type
Visual Basic    
Visual Basic .NET  System.Collections.ArrayList
or
System.Collections.Generic.List(Of type)
 
Python  list 
S-Lang    
Fortrantype :: 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 
SmalltalkArray OrderedCollection 
Windows PowerShelltype[]type[,,...]  
OCamltype arraytype array ... array  
F#type [] or type arraytype [,,...]System.Collections.ArrayList
or
System.Collections.Generic.List<type>
 
Standard MLtype 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 typesAlgebraic data typesUnions
RecordsTuple expression
ALGOL 68struct (modename «fieldname», ...);Required types and operators can be user definedunion (modename, ...);
C (C99)struct «name» {type name;...};N/AN/Aunion {type name;...};
Objective-C
C++struct «name» {type name;...};[b]«std::»tuple<type1..typen>
C#struct name {type name;...}  N/A
JavaN/A[a]  
JavaScript N/A 
Dstruct name {type name;...} std.variant.Algebraic!(type,...)union {type name;...}
Gostruct {
«name» type
...
}
   
Common Lisp (cons val1 val2)[c]  
SchemeN/A  
ISLISP   
Pascalrecord
name: type;
...
end
N/AN/Arecord
case type of
value: (types);
...
end
Visual Basic    
Visual Basic .NETStructure name
Dim name As type
...
End Structure
   
PythonN/A[a]«(»val1, val2, val3, ... «)» N/A
S-Langstruct {name [=value], ...}   
FortranTYPE name
type :: name
...
END TYPE
   
PHPN/A[a]   
PerlN/A[d]  N/A
Perl 6N/A[a]  
RubyOpenStruct.new({:name => value})  
Windows PowerShell    
OCamltype name = {«mutable» name : type;...}«(»val1, val2, val3, ... «)»type name = Foo «of type» | Bar «of type» | ...N/A
F#
Standard MLtype name = {name : type,...}(val1, val2, val3, ... )datatype name = Foo «of type» | Bar «of type» | ...
Haskelldata Name = Constr {name :: type,...}data Name = Foo «types» | Bar «types» | ...

^a Only classes are supported.
^b structs in C++ are actually classes, but have default public visibility and are also POD objects. C++11 extended this further, to make classes act identically to POD objects in many more cases.
^c pair only
^d Although Perl doesn't have records, because Perl's type system allows different data types to be in an array, "hashes" (associative arrays) that don't have a variable index would effectively be the same as records.
^e Enumerations in this language are algebraic types with only nullary constructors

Variable and constant declarations

variableconstanttype synonym
ALGOL 68modename name «:= initial_value»;modename name = value;mode synonym = modename;
C (C99)type name «= initial_value»;enum{ name = value };typedef type synonym;
Objective-C
C++const type name = value;
C#type name «= initial_value»; or
var name = value;
const type name = value; or
readonly type name = value;
using synonym = type;
Dtype name «= initial_value»; or
auto name = value;
const type name = value; or
immutable type name = value;
alias type synonym;
Javatype name «= initial_value»;final type name = value;N/A
JavaScriptvar name «= initial_value»;const name = value;
Govar name type «= initial_value» or
name := initial_value
const name «type» = initial_valuetype 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)N/A
Pascal[a]name: type «= initial_value»name = valuesynonym = type
Visual BasicDim name As typeConst name As type = value 
Visual Basic .NETDim name As type«= initial_value»Imports synonym = type
Pythonname = initial_valueN/Asynonym = type[b]
S-Langname = initial_value; typedef struct {...} typename
Fortrantype nametype, PARAMETER :: name = value 
PHP$name = initial_value;define("name", value);
const name = value (5.3+)
N/A
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
Rubyname = initial_valueName = valuesynonym = type[b]
Windows PowerShell«[type]» $name = initial_value  
OCamllet name «: type ref» = ref value[d]let name «: type» = valuetype synonym = type
F#let mutable name «: type» = value
Standard MLval name «: type ref» = ref value[d]val name «: type» = value
Haskell «name::type;» name = valuetype Synonym = type
ForthVARIABLE name (in some systems use value VARIABLE name instead)value CONSTANT name 

^a Pascal has declaration blocks. See Perbandingan -- 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.

Control flow

Conditional statements

ifelse ifselect caseconditional expression
Adaif condition then
statements
«else
statements»
end if
if condition then
statements
elsif condition then
statements
...
«else
statements»
end if
case expression is
when choice1 => statements
...
«when others => statements»
end case
 
Modula-2case expression is
caseLabelList : statements |
...
«else statements»
end
 
Seed7case expression of
when set1 : statements
...
«otherwise: statements»
end case
 
ALGOL 68 &

"brief form"

if condition then statements «else statements» fiif condition then statements elif condition then statements ficase 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) {
case case1: instructions «break;»
...
«default: instructions»
}
condition ? valueIfTrue : valueIfFalse
Objective-C
C++ (STL)
D
Java
JavaScript
PHP
C#switch (variable) {
case case1: instructions; «jump statement;»
...
«default: instructions; «jump statement;»»
}
Windows PowerShellif (condition) { instructions }
elseif (
condition) { instructions }
...
«else { instructions }»
switch (variable) { case1 { instructions «break;» } ... «default { instructions }»} 
Goif condition {instructions}
«else {instructions}»
if condition {instructions}
else if
condition {instructions}
...
«else {instructions}»
or
switch {
case condition: instructions
...
«default: instructions»
}
switch variable {
case case1: instructions
...
«default: instructions»
}
 
Perlif (condition) {instructions}
«else {instructions}»
or
unless (notcondition) {instructions}
«else {instructions}»
if (condition) {instructions}
elsif (
condition) {instructions}
...
«else {instructions}»
or
unless (notcondition) {instructions}
elsif (
condition) {instructions}
...
«else {instructions}»
use feature "switch";
...
given (variable) {
when (case1) { instructions }
...
«default { instructions }»
}
condition ? valueIfTrue : valueIfFalse
Perl 6if condition {instructions}
«else {instructions}»
or
unless notcondition {instructions}
if condition {instructions}
elsif
condition {instructions}
...
«else {instructions}
given variable {
when case1 { instructions }
...
«default { instructions }»
}
condition ?? valueIfTrue !! valueIfFalse
Rubyif condition
instructions
«else
instructions»
if condition
instructions
elsif condition
instructions
...
«else
instructions»
end
case variable
when case1
instructions
...
«else
instructions»
end
condition ? valueIfTrue : valueIfFalse
Smalltalkcondition ifTrue:
trueBlock
«ifFalse:
falseBlock»
end
  condition ifTrue: trueBlockifFalse: falseBlock
Common Lisp(when condition
instructions)
or
(unless condition
instructions)
or
(if condition
(progn instructions)
«(progn instructions)»)
(cond (condition1 instructions)
(condition2 instructions)
...
«(t instructions)»)
(case expression
(case1 instructions)
(case2 instructions)
...
«(otherwise instructions)»)
(if 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
(progn instructions)
«(progn instructions)»)
(cond (condition1 instructions)
(condition2 instructions)
...
«(t instructions)»)
(case expression
(case1 instructions)
(case2 instructions)
...
«(t instructions)»)
(if condition valueIfTrue valueIfFalse)
Pascalif condition then begin
instructions
end
«else begin
instructions
end»[c]
if condition then begin
instructions
end
else if
condition then begin
instructions
end
...
«else begin
instructions
end»[c]
case variable of
case1: instructions
...
«else: instructions»
end[c]
Visual BasicIf 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
IIf(condition, valueIfTrue, valueIfFalse)
Visual Basic .NETIf(condition, valueIfTrue, valueIfFalse)
Python [a]if condition :
Tab instructions
«else:
Tab instructions»
if condition :
Tab instructions
elif condition :
Tab instructions
...
«else:
Tab instructions»
N/AvalueIfTrue if condition else valueIfFalse
(Python 2.5+)
S-Langif (condition) { instructions } «else { instructions }»if (condition) { instructions } else if (condition) { instructions } ... «else { instructions }»switch (variable) { case case1: instructions } { case case2: instructions } ... 
FortranIF (condition) THEN
instructions
ELSE
instructions
ENDIF
IF (condition) THEN
instructions
ELSEIF (condition) THEN
instructions
...
ELSE
instructions
ENDIF
SELECT CASE(variable)
CASE (case1)
instructions
...
CASE DEFAULT
instructions
END SELECT
 
Forthcondition IF instructions « ELSE instructions» THENcondition IF instructions ELSE condition IF instructions THEN THENvalue CASE
case OF instructions ENDOF
case OF instructions ENDOF
     default instructions
ENDCASE
condition IF valueIfTrue ELSE valueIfFalse THEN
OCamlif condition then begin instructions end «else begin instructions end»if condition then begin instructions end else if condition then begin instructions end ... «else begin instructions end»match value with
pattern1 -> expression
|
pattern2 -> expression
...
«| _ -> expression»[b]
if condition then valueIfTrue else valueIfFalse
F#if condition then
Tab instructions
«else
Tab instructions»
if condition then
Tab instructions
elif condition then
Tab instructions
...
«else
Tab instructions»
Standard MLif condition then «(»instructions «)»
else «(» instructions «)»
if condition then «(»instructions «)»
else if condition then «(» instructions «)»
...
else «(» instructions «)»
case value of
pattern1 => expression
|
pattern2 => expression
...
«| _ => expression»[b]
Haskell (GHC)if condition then expression else expression or
when condition (do instructions) or
unless notcondition (do instructions)
result | condition = expression
| condition = expression
| otherwise = expression
case value of {
pattern1 -> expression;
pattern2 -> expression;
...
«_ -> expression»
}[b]
ifelse ifselect caseconditional expression

^a A single instruction can be written on the same line following the colon. Multiple instructions are grouped together in a block which starts on a newline (The indentation 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.

Loop statements

whiledo whilefor i = first to lastforeach
ALGOL 68«for index» «from first» «by increment» «to last» «while condition» do statements odfor key «to upb list» do «typename val=list[key];» statements od
«while condition»

    do statements od

«while statements; condition»

    do statements od

«for index» «from first» «by increment» «to last» do statements od
C (C99)while (condition) { instructions }do { instructions } while (condition)for («type» i = first; i <= last; ++i) { instructions }N/A
Objective-Cfor (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 }
Javafor (type item : set) { instructions }
JavaScriptfor (var i = first; i <= last; i++) { instructions }for (var index in set) { instructions }
or
for each (var item in set) { instructions } (JS 1.6+)
PHPforeach (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 PowerShellfor ($i = first; $i -le last; $i++) { instructions }foreach (item in set) { instructions using item }
Dforeach (i; first ... last) { instructions }foreach («type» item; set) { instructions }
Gofor condition { instructions } for i := first; i <= last; i++ { instructions }for key, item := range set { instructions }
Perlwhile (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 6while 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 }
Rubywhile condition
instructions
end
or
until notcondition
instructions
end
begin
instructions
end while condition
or
begin
instructions
end until notcondition
for i in first...last
instructions
end
or
first.upto(last-1) { |i| instructions }
for item in set
instructions
end
or
set.each { |item| instructions }
SmalltalkconditionBlock whileTrue:
loopBlock
loopBlock doWhile:
conditionBlock
first to: last do:
loopBlock
collection do:
loopBlock
Common Lisp(loop
while condition
do
instructions)
or
(do () (notcondition)
instructions)
(loop
do
instructions
while condition)
(loop
for i from first to last «by 1»
do
instructions)
or
(dotimes (i N)
instructions)
or
(do ((i first (1+ i))) ((>= i last))
instructions)
(loop
for item in set
do
instructions)
or
(dolist (item set)
instructions)
or
(mapc function list) or
(map 'type function sequence)
Scheme(do () (notcondition) instructions) or
(let loop () (if condition (begin instructions (loop))))
(let loop () (instructions (if condition (loop))))(do ((i first (+ i 1))) ((>= i last)) instructions) or
(let loop ((i first)) (if (< i last) (begin instructions (loop (+ i 1)))))
(for-each (lambda (item) instructions) list)
ISLISP(while condition instructions)(tagbody loop instructions (if condition (go loop))(for ((i first (+ i 1))) ((>= i last)) instructions)(mapc (lambda (item) instructions) list)
Pascalwhile condition do begin
instructions
end
repeat
instructions
until notcondition;
for i := first «step 1» to last do begin
instructions
end;[a]
N/A
Visual BasicDo While condition
instructions
Loop
or
Do Until notcondition
instructions
Loop
Do
instructions
Loop While condition
or
Do
instructions
Loop Until notcondition
For i = first To last «Step 1»
instructions
Next i
For Each item In set
instructions
Next item
Visual Basic .NETFor i «As type» = first To last «Step 1»
instructions
Next i[a]
For Each item As type In set
instructions
Next item
Pythonwhile condition :
Tab instructions
«else:
Tab instructions»
N/Afor i in range(first, last):
Tab instructions
«else:
Tab instructions»
for item in set:
Tab instructions
«else:
Tab instructions»
S-Langwhile (condition) { instructions } «then optional-block»do { instructions } while (condition) «then optional-block»for (i = first; i < last; i++) { instructions } «then optional-block»foreach item(set) «using (what)» { instructions } «then optional-block»
FortranDO WHILE (condition)
instructions
ENDDO
DO
instructions
IF (
condition) EXIT
ENDDO
DO I = first,last
instructions
ENDDO
N/A
ForthBEGIN « instructions » condition WHILE instructions REPEATBEGIN instructions condition UNTILlimit start DO instructions LOOPN/A
OCamlwhile condition do instructions doneN/Afor i = first to last-1 do instructions doneArray.iter (fun item -> instructions) array
List.iter (fun item -> instructions) list
F#while condition do
Tab instructions
N/Afor i = first to last-1 do
Tab instructions
for item in set do
Tab instructions
or
Seq.iter (fun item -> instructions) set
Standard MLwhile condition do ( instructions )N/AArray.app (fn item => instructions) array
app (fn item => instructions) list
Haskell (GHC)N/AControl.Monad.forM_ [0..N-1] (\i -> do instructions)Control.Monad.forM_ list (\item -> do instructions)
Eiffelfrom
setup
until
condition
loop
instructions
end

^a "step n" is used to change the loop interval. If "step" is omitted, then the loop interval is 1.

Exceptions

throwhandlerassertion
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);
Javatry { instructions } catch (exception) { instructions } ... «finally { instructions }»assert condition;
JavaScripttry { instructions } catch (exception) { instructions } «finally { instructions }»?
Dtry { instructions } catch (exception) { instructions } ... «finally { instructions }»assert(condition);
PHPtry { instructions } catch (exception) { instructions } ...assert(condition);
S-Langtry { instructions } catch «exception» { instructions } ... «finally { instructions }»?
Windows PowerShelltrap «[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);
Perldie exception;eval { instructions }; if ($@) { instructions }?
Perl 6try { instructions CATCH { when exception { instructions } ...}}?
Rubyraise exceptionbegin
instructions
rescue exception
instructions
...
«else
instructions»
«ensure
instructions»
end
 
Smalltalkexception raiseinstructionBlock on: exception do: handlerBlockassert: conditionBlock
Common Lisp(error "exception") or
(error (make-condition
type
arguments))
(handler-case
(progn instructions)
(exception instructions)
...)
or
(handler-bind
(condition
(lambda
instructions
«invoke-restart restart args»))
...)[a]
(assert condition) or
(assert condition
«(place)
«error»»)
or
(check-type var type)
Scheme (R6RS)(raise exception)(guard (con (condition instructions) ...) instructions)?
ISLISP(error "error-string" objects) or
(signal-condition condition continuable)
(with-handler
handler form*)
?
Pascalraise Exception.Create()try Except on E: exception do begin instructions end; end;?
Visual BasicErr.Raise ERRORNUMBERWith New Try: On Error Resume Next
OneInstruction
.Catch: On Error GoTo 0: Select Case .Number
Case ERRORNUMBER
instructions
End Select: End With

'*** Try class ***
Private mstrDescription As String
Private mlngNumber As Long
Public Sub Catch()
mstrDescription = Err.Description
mlngNumber = Err.Number
End Sub
Public Property Get Number() As Long
Number = mlngNumber
End Property
Public Property Get Description() As String
Description = mstrDescription
End Property

https://sites.google.com/site/truetry forvisualbasic/

Debug.Assert condition
Visual Basic .NETThrow exceptionTry
instructions
Catch «exception» «When condition»
instructions
...
«Finally
instructions»
End Try
Debug.Assert(condition)
Pythonraise exceptiontry:
Tab instructions
except «exception»:
Tab instructions
...
«else:
Tab instructions»
«finally:
Tab instructions»
assert condition
FortranN/A
Forthcode THROWxt CATCH ( code or 0 )N/A
OCamlraise exceptiontry expression with pattern -> expression ...assert condition
F#try expression with pattern -> expression ...
or
try expression finally expression
Standard MLraise 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.

Other control flow statements

exit block(break)continuelabelbranch (goto)return value from generator
ALGOL 68value exit; ...do statements; skip exit; label: statements odlabel: ...go to label; ...

goto label; ...
label; ...

yield(value)

(Callback - example)

C (C99)break;continue;label:goto label;N/A
Objective-C
C++ (STL)
D
C#yield return value;
Javabreak «label»;continue «label»;N/A 
JavaScriptyield value«;»
PHPbreak «levels»;continue «levels»;goto label; 
Perllast «label»;next «label»; 
Perl 6 
Gobreak «label»continue «label»goto label 
Common Lisp(return) or
(return-from block) or
(loop-finish)
 (tagbody tag
...
tag
...)
(go tag) 
Scheme     
ISLISP(return-from block) (tagbody tag
...
tag
...)
(go tag) 
Pascal(ISO)N/Alabel:[a]goto label;N/A
Pascal(FPC)break;continue;
Visual BasicExit blockN/Alabel:GoTo label
Visual Basic .NETContinue block
PythonbreakcontinueN/Ayield value
RPG IVLEAVE;ITER;   
S-Langbreak;continue;   
FortranEXITCYCLElabel[b]GOTO labelN/A
Rubybreaknext   
Windows PowerShellbreak« label»continue   
OCamlN/A 
F# 
Standard ML 
Haskell (GHC) 

^a Pascal has declaration blocks. See Perbandingan -- programming languages (basic instructions)#Functions.
^b label must be a number between 1 and 99999.

Functions

See reflection for calling and declaring functions by strings.

calling a functionbasic/void functionvalue-returning functionrequired main function
ALGOL 68foo«(parameters)»;proc foo = «(parameters)» void: ( instructions );proc foo = «(parameters)» rettype: ( instructions ...; retvalue );N/A
C (C99)foo(«parameters»)void foo(«parameters») { instructions }type foo(«parameters») { instructions ... return value; }«global declarations»
int main(«int argc, char *argv[]») {
instructions
}
Objective-C
C++ (STL)
C#static void Main(«string[] args») { instructions } or
static int Main(«string[] args») { instructions }
Javapublic static void main(String[] args) { instructions } or
public static void main(String... args) { instructions }
Dint main(«char[][] args») { instructions} or
int main(«string[] args») { instructions} or
void main(«char[][] args») { instructions} or
void main(«string[] args») { instructions}
JavaScriptfunction foo(«parameters») { instructions } or
var foo = function («parameters») {instructions } or
var foo = new Function («"parameter", ... ,"last parameter"» "instructions");
function foo(«parameters») { instructions ... return value; }N/A
Gofunc foo(«parameters») { instructions }func foo(«parameters») type { instructions ... return value }func main() { instructions }
Common Lisp(foo «parameters»)(defun foo («parameters»)
instructions)
or
(setf (symbol-function 'symbol)
lambda)
(defun foo («parameters»)
...
value)
N/A
Scheme(define (foo parameters) instructions) or
(define foo (lambda (parameters) instructions))
(define (foo parameters) instructions... return_value) or
(define foo (lambda (parameters) instructions... return_value))
ISLISP(defun foo («parameters»)
instructions)
(defun foo («parameters»)
...
value)
Pascalfoo«(parameters)»procedure foo«(parameters)»; «forward;»[a]
«label
label declarations»
«const
constant declarations»
«type
type declarations»
«var
variable declarations»
«local function declarations»
begin
instructions
end;
function foo«(parameters)»: type; «forward;»[a]
«label
label declarations»
«const
constant declarations»
«type
type declarations»
«var
variable declarations»
«local function declarations»
begin
instructions;
foo :=
value
end;
program name;
«label
label declarations»
«const
constant declarations»
«type
type declarations»
«var
variable declarations»
«function declarations»
begin
instructions
end.
Visual BasicFoo(«parameters»)Sub Foo(«parameters»)
instructions
End Sub
Function Foo(«parameters») As type
instructions
Foo = value
End Function
Sub Main()
instructions
End Sub
Visual Basic .NETFunction 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
Pythonfoo(«parameters»)def foo(«parameters»):
Tab instructions
def foo(«parameters»):
Tab instructions
Tab return value
N/A
S-Langfoo(«parameters» «;qualifiers»)define foo («parameters») { instructions }define foo («parameters») { instructions ... return value; }public define slsh_main () { instructions }
Fortranfoo («arguments»)
CALL sub_foo (
«arguments»)[c]
SUBROUTINE sub_foo («arguments»)
instructions
END SUBROUTINE[c]
type FUNCTION foo («arguments»)
instructions
...
foo
= value
END FUNCTION[c]
PROGRAM main
instructions
END PROGRAM
Forth«parameters» FOO: FOO « stack effect comment: ( before -- ) »
instructions
 
: FOO « stack effect comment: ( before -- after ) »
instructions
 
N/A
PHPfoo(«parameters»)function foo(«parameters») { instructions }function foo(«parameters») { instructions ... return value; }N/A
Perlfoo(«parameters») or
&foo«(parameters)»
sub foo { «my (parameters) = @_;» instructions }sub foo { «my (parameters) = @_;» instructions... «return» value; }
Perl 6foo(«parameters») or
&foo«(parameters)»
«multi »sub foo(parameters) { instructions }«our «type» »«multi »sub foo(parameters) { instructions... «return» value; }
Rubyfoo«(parameters)»def foo«(parameters)»
instructions
end
def foo«(parameters)»
instructions
«return» value
end
Windows PowerShellfoo« parameters»function foo «(parameters)» { instructions }; or
function foo { «param(parameters)» instructions }
function foo «(parameters)» { instructions … return value }; or
function foo { «param(parameters)» instructionsreturn value }
OCamlfoo parameterslet «rec» foo parameters = instructionslet «rec» foo parameters = instructions... return_value
F#[<EntryPoint>] let main args = instructions
Standard MLfun foo parameters = ( instructions )fun foo parameters = ( instructions... return_value ) 
Haskellfoo parameters = do
Tab instructions
foo parameters = return_value
or
foo parameters = do
Tab instructions
Tab return value
«main :: IO ()»
main = do instructions
Eiffelfoo («parameters»)foo («parameters»)
require
preconditions
do
instructions
ensure
postconditions
end
foo («parameters»): type
require
preconditions
do
instructions
Result := value
ensure
postconditions
end
[b]

^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.

[c]

Type conversions

Where string is a signed decimal number:

string to integerstring to long integerstring to floating pointinteger to stringfloating point to string
ALGOL 68 with general, and then specific formatsWith prior declarations and association of: string buf := "12345678.9012e34 "; file proxy; associate(proxy, buf);
get(proxy, ivar);get(proxy, livar);get(proxy, rvar);put(proxy, ival);put(proxy, rval);
getf(proxy, ($g$, ivar)); or

getf(proxy, ($dddd$, ivar));

getf(proxy, ($g$, livar)); or

getf(proxy, ($8d$, livar));

getf(proxy, ($g$, rvar)); or

getf(proxy, ($8d.4dE2d$, rvar));

putf(proxy, ($g$, ival)); or

putf(proxy, ($4d$, ival));

putf(proxy, ($g(width, places, exp)$, rval)); or

putf(proxy, ($8d.4dE2d$, rval)); etc.

C (C99)integer = atoi(string);long = atol(string);float = atof(string);sprintf(string, "%i", integer);sprintf(string, "%f", float);
Objective-Cinteger = [string intValue];long = [string longLongValue];float = [string doubleValue];string = [NSString stringWithFormat:@"%i", integer];string = [NSString stringWithFormat:@"%f", float];
C++ (STL)«std::»istringstream(string) >> number;«std::»ostringstream o; o << number; string = o.str();
C++11integer = «std::»stoi(string);long = «std::»stol(string);float = «std::»stof(string);

double = «std::»stod(string);

string = «std::»to_string(number);
C#integer = int.Parse(string);long = long.Parse(string);float = float.Parse(string); or
double = double.Parse(string);
string = number.ToString();
Dinteger = std.conv.to!int(string)long = std.conv.to!long(string)float = std.conv.to!float(string) or
double = std.conv.to!double(string)
string = std.conv.to!string(number)
Javainteger = 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[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+"";
Gointeger, error = strconv.Atoi(string) or
integer, error = strconv.ParseInt(string, 10, 0)
long, error = strconv.ParseInt(string, 10, 64)float, error = strconv.ParseFloat(string, 64)string = strconv.Itoa(integer) or
string = strconv.FormatInt(integer, 10) or
string = fmt.Sprint(integer)
string = strconv.FormatFloat(float) or
string = fmt.Sprint(float)
Common Lisp(setf integer (parse-integer string))(setf float (read-from-string string))(setf string (princ-to-string number))
Scheme(define number (string->number string))(define string (number->string number))
ISLISP(setf integer (convert string <integer>))(setf float (convert string <float>))(setf string (convert number <string>))
Pascalinteger := StrToInt(string); float := StrToFloat(string);string := IntToStr(integer);string := FloatToStr(float);
Visual Basicinteger = CInt(string)long = CLng(string)float = CSng(string) or
double = CDbl(string)
string = CStr(number)
Visual Basic .NET
Pythoninteger = int(string)long = long(string)float = float(string)string = str(number)
S-Langinteger = atoi(string);long = atol(string);float = atof(string);string = string(number);
FortranREAD(string,format) numberWRITE(string,format) number
PHPinteger = intval(string); 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 6number = +string;string = ~number;
Rubyinteger = string.to_i or
integer = Integer(string)
float = string.to_f or
float = Float(string)
string = number.to_s
Windows PowerShellinteger = [int]stringlong = [long]stringfloat = [float]stringstring = [string]number; or
string = "number"; or
string = (number).ToString()
OCamllet integer = int_of_string string let float = float_of_string stringlet string = string_of_int integerlet string = string_of_float float
F#let integer = int stringlet integer = int64 stringlet float = float stringlet string = string number
Standard MLval integer = Int.fromString string val float = Real.fromString stringval string = Int.toString integerval string = Real.toString float
Haskell (GHC)number = read stringstring = show number

^a JavaScript only uses floating point numbers so there are some technicalities.[4]
^b Perl doesn't have separate types. Strings and numbers are interchangeable.

Standard stream I/O

read fromwrite to
stdinstdoutstderr
ALGOL 68readf(($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-Cdata = [[NSFileHandle fileHandleWithStandardInput] readDataToEndOfFile];[[NSFileHandle fileHandleWithStandardOutput] writeData:data];[[NSFileHandle fileHandleWithStandardError] writeData:data];
C++«std::»cin >> x; or
«std::»getline(«std::»cin, str);
«std::»cout << x;«std::»cerr << x; or
«std::»clog << x;
C#x = Console.Read(); or
x = Console.ReadLine();
Console.Write(«format, »x); or
Console.WriteLine(«format, »x);
Console.Error.Write(«format, »x); or
Console.Error.WriteLine(«format, »x);
Dx = std.stdio.readln()std.stdio.write(x) or
std.stdio.writeln(x) or
std.stdio.writef(format, x) or
std.stdio.writefln(format, x)
stderr.write(x) or
stderr.writeln(x) or
std.stdio.writef(stderr, format, x) or
std.stdio.writefln(stderr, format, x)
Javax = System.in.read(); or
x = new Scanner(System.in).nextInt(); or
x = new Scanner(System.in).nextLine();
System.out.print(x); or
System.out.printf(format, x); or
System.out.println(x);
System.err.print(x); or
System.err.printf(format, x); or
System.err.println(x);
Gofmt.Scan(&x) or
fmt.Scanf(format, &x) or
x = bufio.NewReader(os.Stdin).ReadString( '\n')
fmt.Println(x) or
fmt.Printf(format, x)
fmt.Fprintln(os.Stderr, x) or
fmt.Fprintf(os.Stderr, format, x)
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)
Pascalread(x); or
readln(x);
write(x); or
writeln(x);
N/A
Visual BasicInput« prompt,» xPrint x or
? x
Visual Basic .NETx = 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 2.xx = raw_input(«prompt»)print x or
sys.stdout.write(x)
print >> sys.stderr, x or
sys.stderr.write(x)
Python 3.xx = input(«prompt»)print(, end=""»)print(, end=""», file=sys.stderr)
S-Langfgets (&x, stdin)fputs (x, stdout)fputs (x, stderr)
FortranREAD(*,format) variable names or
READ(INPUT_UNIT,
format) variable names[e]
WRITE(*,format) expressions or
WRITE(OUTPUT_UNIT,
format) expressions[e]
WRITE(ERROR_UNIT,format) expressions[e]
Forthbuffer length ACCEPT ( # chars read )
KEY ( char )
buffer length TYPE
char EMIT
N/A
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)
Rubyx = getsputs 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
OCamllet x = read_int () or
let str = read_line () or
Scanf.scanf format (fun x ... -> ...)
print_int x or
print_endline str or
Printf.printf format x ...
prerr_int x or
prerr_endline str or
Printf.eprintf format x ...
F#let x = System.Console.ReadLine()printf format x ... or
printfn format x ...
eprintf format x ... or
eprintfn format x ...
Standard MLval str = TextIO.inputLIne TextIO.stdInprint strTextIO.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.[7]

Reading command-line arguments

Argument valuesArgument countsProgram name / Script name
C (C99)argv[n]argcfirst argument
Objective-C
C++
C#args[n]args.LengthAssembly.GetEntryAssembly().Location;
Javaargs.length 
Dfirst argument
JavaScript
Windows Script Host implementation
WScript.Arguments(n)WScript.Arguments.lengthWScript.ScriptName or WScript.ScriptFullName
Goos.Args[n]len(os.Args)first argument
Common Lisp???
Scheme (R6RS)(list-ref (command-line) n)(length (command-line))first argument
ISLISPN/AN/AN/A
PascalParamStr(n)ParamCountfirst argument
Visual BasicCommand[a]N/AApp.Path
Visual Basic .NETCmdArgs(n)CmdArgs.Length[Assembly].GetEntryAssembly().Locatio n
Pythonsys.argv[n]len(sys.argv)first argument
S-Lang__argv[n]__argcfirst argument
FortranDO i = 1,argc
CALL GET_COMMAND_ARGUMENT (i,argv(i))
ENDDO
argc = COMMAND_ARGUMENT_COUNT ()CALL GET_COMMAND_ARGUMENT (0,progname)
PHP$argv[n]$argcfirst argument
Perl$ARGV[n]scalar(@ARGV)$0
Perl 6@*ARGS[n]@*ARGS.elems$PROGRAM_NAME
RubyARGV[n]ARGV.size$0
Windows PowerShell$args[n]$args.Length$MyInvocation.MyCommand.Name
OCamlSys.argv.(n)Array.length Sys.argvfirst argument
F#args.[n]args.LengthAssembly.GetEntryAssembly().Location
Standard MLList.nth (CommandLine.arguments (), n)length (CommandLine.arguments ())CommandLine.name ()
Haskell (GHC)do { args <- System.getArgs; return 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 commandExecute programReplace current program with new executed program
Csystem("command"); execl(path, args); or
execv(path, arglist);
C++ 
Objective-C[NSTask launchedTaskWithLaunchPath:(NSString *)path arguments:(NSArray *)arguments]; 
C# System.Diagnostics.Process.Start(path, argstring); 
F#  
Go exec.Run(path, argv, envv, dir, exec.DevNull, exec.DevNull, exec.DevNull)os.Exec(path, argv, envv)
Visual BasicInteraction.Shell(command «WindowStyle» «isWaitOnReturn»)  
Visual Basic .NETMicrosoft.VisualBasic.Interaction.She ll(command «WindowStyle» «isWaitOnReturn»)System.Diagnostics.Process.Start(path, argstring) 
Dstd.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)  
ISLISPN/AN/AN/A
Pascalsystem(command);  
OCamlSys.command command, Unix.open_process_full command env (stdout, stdin, stderr),...Unix.create_process prog args new_stdin new_stdout new_stderr, ...Unix.execv prog args or
Unix.execve prog args env
Standard MLOS.Process.system commandUnix.execute (path, args)Posix.Process.exec (path, args)
Haskell (GHC)System.system commandSystem.Process.runProcess path args ...Posix.Process.executeFile path True args ...
Perlsystem(command) or
$output = `command`
 exec(path, args)
Rubysystem(command) or
output = `command`
 exec(path, args)
PHPsystem(command) or
$output = `command` or
exec(command) or
passthru(command)
  
Pythonos.system(command) or
subprocess.Popen(command)
 os.execv(path, args)
S-Langsystem(command)  
FortranCALL SYSTEM (command, status) or
status = SYSTEM (command)[a]
  
Windows PowerShell[Diagnostics.Process]::Start(command)«Invoke-Item »program arg1 arg2 … 

^a Compiler-dependent extension.[8]

References

(Sebelumnya) Comparison of programming lang ...Comparison of programming lang ... (Berikutnya)