赛派号

鱼跃制氧机隔几秒响一次 Comparison of programming languages (basic instructions)

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: "Comparison of programming languages" basic instructions – news · newspapers · books · scholar · JSTOR (February 2009) (Learn how and when to remove this message) Comparison ofprogramming languages General comparison Assignment Basic syntax Basic instructions Comments Control flow Foreach loops While loops For loops Do-while Exception handling Enumerated types Algebraic data types Generators Anonymous functions Conditional expressions Arrays Associative arrays Scope String operations String functions Higher-order functions Filter Fold Map Type systems Dependent types List comprehension Object-oriented programming Object-oriented constructors Operators Ternary conditional operator Null coalescing operators Safe nigation operators Modulo operators Evaluation strategy List of "Hello World" programs Comparison of individuallanguages ALGOL 58's influence on ALGOL 60 ALGOL 60: Comparisons with other languages ALGOL 68: Comparisons with other languages Compatibility of C and C++ Comparison of Pascal and Borland Delphi Comparison of Object Pascal and C Comparison of Pascal and C Comparison of Ja and C++ Comparison of C# and Ja Comparison of C# and Visual Basic .NET Comparison of Visual Basic and Visual Basic .NET vte

This article compares a large number of programming languages by tabulating their data types, their expression, statement, and declaration syntax, and some common operating-system interfaces.

Conventions of this article[edit]

Generally, var, var, or var is how variable names or other non-literal values to be interpreted by the reader are represented. The rest is literal code. Guillemets (« and ») enclose optional sections. Tab ↹ indicates a necessary (whitespace) indentation.

The tables are not sorted lexicographically ascending by programming language name by default, and that some languages he entries in some tables but not others.

Type identifiers[edit] Integers[edit] 8 bit (byte) 16 bit (short integer) 32 bit 64 bit (long integer) Word size Arbitrarily precise (bignum) Signed Unsigned Signed Unsigned Signed Unsigned Signed Unsigned Signed Unsigned Ada[1] range -2**7 .. 2**7 - 1[j] range 0 .. 2**8 - 1[j] or mod 2**8[k] range -2**15 .. 2**15 - 1[j] range 0 .. 2**16 - 1[j] or mod 2**16[k] range -2**31 .. 2**31 - 1[j] range 0 .. 2**32 - 1[j] or mod 2**32[k] range -2**63 .. 2**63 - 1[j] mod 2**64[k] Integer[j] range 0 .. 2**Integer'Size - 1[j] or mod Integer'Size[k] —N/a ALGOL 68 (variable-width) short short int[c] —N/a short int[c] —N/a int[c] —N/a long int[c] —N/a int[c] —N/a long long int[a][g] bytes and bits C (C99 fixed-width) int8_t uint8_t int16_t uint16_t int32_t uint32_t int64_t uint64_t intptr_t[c] size_t[c] —N/a C++ (C++11 fixed-width) C (C99 variable-width) signed char unsigned char, byte (C++17) short[c] unsigned short[c] long[c] unsigned long[c] long long[c] unsigned long long[c] int[c] unsigned int[c] C++ (C++11 variable-width) Objective-C (Cocoa) signed char or int8_t unsigned char or uint8_t short or int16_t unsigned short or uint16_t int or int32_t unsigned int or uint32_t long long or int64_t unsigned long long or uint64_t NSInteger or long NSUInteger or unsigned long C# sbyte byte short ushort int uint long ulong IntPtr UIntPtr System.Numerics.BigInteger(.NET 4.0) Ja byte —N/a char[b] —N/a —N/a —N/a —N/a ja.math.BigInteger Go int8 uint8 or byte int16 uint16 int32 uint32 int64 uint64 int uint big.Int Rust i8 u8 i16 u16 i32 u32 i64 u64 isize usize —N/a Swift Int8 UInt8 Int16 UInt16 Int32 UInt32 Int64 UInt64 Int UInt D byte ubyte short ushort int uint long ulong —N/a —N/a BigInt Common Lisp[2] (signed-byte 8) (unsigned-byte 8) (signed-byte 16) (unsigned-byte 16) (signed-byte 32) (unsigned-byte 32) (signed-byte 64) (unsigned-byte 64) bignum Scheme ISLISP[3] bignum Pascal (FPC) shortint byte smallint word longint longword int64 qword integer cardinal —N/a Visual Basic —N/a Byte Integer —N/a Long —N/a —N/a —N/a —N/a Visual Basic .NET SByte Short UShort Integer UInteger Long ULong System.Numerics.BigInteger(.NET 4.0) FreeBasic Byte or Integer UByte or UInteger Short or Integer UShort or UInteger Long or Integer ULong or UInteger LongInt or Integer ULongInt or UInteger Integer UInteger —N/a Python 2.x —N/a —N/a —N/a —N/a int —N/a long Python 3.x —N/a —N/a —N/a —N/a —N/a int S-Lang —N/a —N/a —N/a —N/a —N/a —N/a Fortran INTEGER(KIND = n)[f] —N/a INTEGER(KIND = n)[f] —N/a INTEGER(KIND = n)[f] —N/a INTEGER(KIND = n)[f] —N/a PHP —N/a —N/a int[m] —N/a int[m] —N/a —N/a [e] Perl 5 —N/a[d] —N/a[d] —N/a[d] —N/a[d] —N/a[d] Math::BigInt Raku int8 uint8 int16 uint16 int32 uint32 int64 uint64 Int —N/a Ruby —N/a —N/a —N/a —N/a Fixnum —N/a Bignum Erlang[n] —N/a —N/a —N/a —N/a integer() —N/a integer()[o] Scala Byte —N/a Short Char[l] Int —N/a Long —N/a —N/a —N/a scala.math.BigInt Seed7 —N/a —N/a —N/a —N/a —N/a —N/a integer —N/a —N/a —N/a bigInteger Smalltalk —N/a —N/a —N/a —N/a SmallInteger[i] —N/a LargeInteger[i] Windows PowerShell —N/a —N/a —N/a —N/a —N/a —N/a OCaml —N/a —N/a int32 —N/a int64 —N/a int or nativeint open Big_int;; or big_int F# sbyte byte int16 uint16 int32 or int uint32 uint64 nativeint unativeint bigint Standard ML —N/a Word8.word —N/a Int32.int Word32.word Int64.int Word64.word int word LargeInt.int orIntInf.int Haskell (GHC) «import Int» or Int8 «import Word» or Word8 «import Int» or Int16 «import Word» or Word16 «import Int» or Int32 «import Word» or Word32 «import Int» or Int64 «import Word» or Word64 Int «import Word» or Word Integer Eiffel INTEGER_8 NATURAL_8 INTEGER_16 NATURAL_16 INTEGER_32 NATURAL_32 INTEGER_64 NATURAL_64 INTEGER NATURAL —N/a 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 —N/a —N/a —N/a Mathematica —N/a —N/a —N/a —N/a —N/a Integer Wolfram Language —N/a —N/a —N/a —N/a —N/a Integer ^a The standard constants int shorts and int lengths can be used to determine how many shorts and longs can be usefully prefixed to short int and long int. The actual sizes of short int, int, and long int are ailable as the constants short max int, max int, and long max int etc. ^b Commonly used for characters. ^c The ALGOL 68, C and C++ languages do not specify the exact width of the integer types short, int, long, and (C99, C++11) long long, so they are implementation-dependent. In C and C++ short, long, and long long types are required to be at least 16, 32, and 64 bits wide, respectively, but can be more. The int type is required to be at least as wide as short and at most as wide as long, and is typically the width of the word size on the processor of the machine (i.e. on a 32-bit machine it is often 32 bits wide; on 64-bit machines it is sometimes 64 bits wide). C99 and C++11[citation needed] also define the [u]intN_t exact-width types in the stdint.h header. See C syntax#Integral types for more information. In addition the types size_t and ptrdiff_t are defined in relation to the address size to hold unsigned and signed integers sufficiently large to handle array indices and the difference between pointers. ^d Perl 5 does not he distinct types. Integers, floating point numbers, strings, etc. are all considered "scalars". ^e PHP has two arbitrary-precision libraries. The BCMath library just uses strings as datatype. The GMP library uses an internal "resource" type. ^f The value of n is provided by the SELECTED_INT_KIND[4] intrinsic function. ^g ALGOL 68G's runtime option --precision "number" can set precision for long long ints to the required "number" significant digits. The standard constants long long int width and long long max int can be used to determine actual precision. ^h COBOL allows the specification of a required precision and will automatically select an ailable type capable of representing the specified precision. "PIC S9999", for example, would require a signed variable of four decimal digits precision. If specified as a binary field, this would select a 16-bit signed type on most platforms. ^i Smalltalk automatically chooses an appropriate representation for integral numbers. Typically, two representations are present, one for integers fitting the native word size minus any tag bit (SmallInteger) and one supporting arbitrary sized integers (LargeInteger). Arithmetic operations support polymorphic arguments and return the result in the most appropriate compact representation. ^j Ada range types are checked for boundary violations at run-time (as well as at compile-time for static expressions). Run-time boundary violations raise a "constraint error" exception. Ranges are not restricted to powers of two. Commonly predefined Integer subtypes are: Positive (range 1 .. Integer'Last) and Natural (range 0 .. Integer'Last). Short_Short_Integer (8 bits), Short_Integer (16 bits) and Long_Integer (64 bits) are also commonly predefined, but not required by the Ada standard. Runtime checks can be disabled if performance is more important than integrity checks. ^k Ada modulo types implement modulo arithmetic in all operations, i.e. no range violations are possible. Modulos are not restricted to powers of two. ^l Commonly used for characters like Ja's char. ^m int in PHP has the same width as long type in C has on that system.[c] ^n Erlang is dynamically typed. The type identifiers are usually used to specify types of record fields and the argument and return types of functions.[5] ^o When it exceeds one word.[6] Floating point[edit] Single precision Double precision Other precision Processor dependent Ada[1] Float Long_Float —N/a ALGOL 68 real[a] long real[a] short real, long long real, etc.[d] C float[b] double long double[f] C++ (STL) Objective-C (Cocoa) CGFloat C# float —N/a Ja Go float32 float64 Rust f32 f64 f16, f128 Swift Float or Float32 Double or Float64 Float80[g] CGFloat D float double real Common Lisp single-float double-float float, short-float, long-float Scheme ISLISP Pascal (FPC) single double real Visual Basic Single Double —N/a Visual Basic .NET Xojo Python —N/a float JaScript Number[7] —N/a S-Lang Fortran REAL(KIND = n)[c] PHP float Perl Raku num32 num64 Num Ruby —N/a Float —N/a Scala Float Double Seed7 —N/a float Smalltalk Float Double Windows PowerShell OCaml —N/a float —N/a F# float32 Standard ML —N/a real Haskell (GHC) Float Double Eiffel REAL_32 REAL_64 COBOL FLOAT-BINARY-7[e] FLOAT-BINARY-34[e] FLOAT-SHORT, FLOAT-LONG, FLOAT-EXTENDED Mathematica —N/a —N/a Real ^a The standard constants real shorts and real lengths can be used to determine how many shorts and longs can be usefully prefixed to short real and long real. The actual sizes of short real, real, and long real are ailable as the constants short max real, max real and long max real etc. With the constants short small real, small real and long small real ailable for each type's machine epsilon. ^b declarations of single precision often are not honored ^c The value of n is provided by the SELECTED_REAL_KIND[8] intrinsic function. ^d ALGOL 68G's runtime option --precision "number" can set precision for long long reals to the required "number" significant digits. The standard constants long long real width and long long max real can be used to determine actual precision. ^e These IEEE floating-point types will be introduced in the next COBOL standard. ^f Same size as double on many implementations. ^g Swift supports 80-bit extended precision floating point type, equivalent to long double in C languages. Complex numbers[edit] Integer Single precision Double precision Half and Quadruple precision etc. Ada[1] —N/a Complex[b] Complex[b] Complex[b] ALGOL 68 —N/a compl long compl etc. short compl etc. and long long compl etc. C (C99)[9] —N/a float complex double complex —N/a C++ (STL) —N/a std::complex std::complex C# —N/a —N/a System.Numerics.Complex(.NET 4.0) Ja —N/a —N/a —N/a Go —N/a complex64 complex128 D —N/a cfloat cdouble Objective-C —N/a —N/a —N/a Common Lisp (complex integer) (complex single-float) (complex double-float) complex Scheme —N/a Pascal —N/a —N/a Visual Basic —N/a —N/a Visual Basic .NET —N/a —N/a System.Numerics.Complex(.NET 4.0) Perl Math::Complex Raku complex64 complex128 Complex Python complex —N/a JaScript —N/a —N/a S-Lang —N/a —N/a Fortran COMPLEX(KIND = n)[a] Ruby Complex —N/a Complex Scala —N/a —N/a —N/a Seed7 —N/a —N/a complex Smalltalk Complex Complex Complex Windows PowerShell —N/a —N/a OCaml —N/a —N/a Complex.t F# System.Numerics.Complex(.NET 4.0) Standard ML —N/a —N/a —N/a Haskell (GHC) —N/a Complex.Complex Float Complex.Complex Double Eiffel —N/a —N/a —N/a COBOL —N/a —N/a —N/a Mathematica Complex —N/a —N/a Complex ^a The value of n is provided by the SELECTED_REAL_KIND[8] intrinsic function. ^b Generic type which can be instantiated with any base floating point type. Other variable types[edit] Text Boolean Enumeration Object/Universal Character String[a] Ada[1] Character String, Bounded_String, Unbounded_String Boolean (item1, item2, ...) tagged null record ALGOL 68 char string, bytes bool, bits N/A - User defined N/A C (C99) char, wchar_t N/A bool[b] enum «name» { item1, item2, ... }; void * C++ (STL) «std::»string Objective-C unichar NSString * BOOL id C# char string bool enum name { item1« = value», item2« = value», ... } object Ja String boolean enum name { item1, item2, ... } Object Go byte, rune string bool const (   item1 = iota   item2   ...) interface{} Rust char String bool enum name { item1« = value», item2« = value», ... } std::any::Any Swift Character String Bool enum name { case item1, item2, ... } Any D char string bool enum name { item1, item2, ... } std.variant.Variant Common Lisp character string boolean (member item1 item2 ...) t Scheme ISLISP Pascal (ISO) char N/A boolean ( item1, item2, ... ) N/A Object Pascal (Delphi) string variant Visual Basic N/A String Boolean Enum name   item1 «= value»   item2 «= value»   ...End Enum Variant Visual Basic .NET Char Object Xojo N/A Object or Variant Python N/A[d] str bool from enum import Enum class Name(Enum): item1 = value item2 = value ... object JaScript N/A[d] String Boolean Object S-Lang Fortran CHARACTER(LEN = *) CHARACTER(LEN = :), allocatable LOGICAL(KIND = n)[f] CLASS(*) PHP N/A[d] string bool (type declaration omitted) Perl N/A[d] UNIVERSAL Raku Char Str Bool enum nameenum name «:item1(value) :item2(value) ..» Mu Ruby N/A[d] String Object[c] Object Scala Char String Boolean object name extends Enumeration {   val item1, item2, ... = Value} Any Seed7 char string boolean const type: name is new enum   item1,   item2,   ...end enum; Windows PowerShell OCaml char string bool N/A[e] N/A F# type name = item1 = value |item2 = value | ... obj Standard ML N/A[e] N/A Haskell (GHC) Char String Bool N/A[e] N/A Eiffel CHARACTER STRING BOOLEAN N/A ANY COBOL PIC X PIC X(string length) or PIC X«X...» PIC 1«(number of digits)» or PIC 1«1...» N/A OBJECT REFERENCE Mathematica N/A[d] String N/A ^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 he a separate character type. Characters are represented as strings of length 1. ^e Enumerations in this language are algebraic types with only nullary constructors ^f The value of n is provided by the SELECTED_INT_KIND[4] intrinsic function. Derived types[edit] Array[edit] Further information: Comparison of programming languages (array) fixed size array dynamic size array one-dimensional array multidimensional array one-dimensional array multidimensional array Ada[1] array ( .. ) of orarray () of array ( .. , .. , ...) of orarray (, , ...) of array ( range ) of array ( range , range , ...) of ALGOL 68 [first:last]«modename»or simply:[size]«modename» [first1:last1, first2:last2]«modename»or[first1:last1][first2:last2]«modename»etc. flex[first:last]«modename»or simply:flex[size]«modename» flex[first1:last1, first2:last2]«modename»orflex[first1:last1]flex[first2:last2]«modename» etc. C (C99) type name[size][a] type name[size1][size2][a] type *nameor within a block:int n = ...; type name[n] C++ (STL) «std::»array(C++11) «std::»vector C# type[] type[,,...] System.Collections.ArrayListorSystem.Collections.Generic.List Ja type[][b] type[][]...[b] ArrayList or ArrayList D type[size] type[size1][size2] type[] Go [size]type [size1][size2]...type []type [][]type Rust [type; size] [[type; size1]; size2] Vec Vec Swift [type] or Array [[type]] or Array Objective-C NSArray NSMutableArray JaScript —N/a —N/a Array[d] Common Lisp (simple-array type (dimension)) (simple-array type (dimension1 dimension2)) (array type (dimension)) (array type (dimension1 dimension2)) Scheme ISLISP Pascal array[first..last] of type[c] array[first1..last1] of array[first2..last2] ... of type[c]or array[first1..last1, first2..last2, ...] of type[c] —N/a —N/a Object Pascal (Delphi) array of type array of array ... of type Visual Basic Dim x(last) As type Dim x(last1, last2,...) As type Visual Basic .NET type() type(,,...) System.Collections.ArrayListorSystem.Collections.Generic.List(Of type) Python list S-Lang x = type[size]; x = type[size1, size2, ...]; Fortran type :: name(size) type :: name(size1, size2,...) type, ALLOCATABLE :: name(:) type, ALLOCATABLE :: name(:,:,...) PHP array Perl Raku Array[type] or Array of type Ruby x = Array.new(size1){ Array.new(size2) } Array Scala Array[type] Array[...[Array[type]]...] ArrayBuffer[type] Seed7 array typeorarray [idxType] type array array typeorarray [idxType] array [idxType] type array typeorarray [idxType] type array array typeorarray [idxType] array [idxType] type Smalltalk Array OrderedCollection Windows PowerShell type[] type[,,...] OCaml type array type array ... array F# type []ortype array type [,,...] System.Collections.ArrayListorSystem.Collections.Generic.List Standard ML type vector or type array Haskell (GHC) x = Array.array (0, size-1) list_of_association_pairs x = Array.array ((0, 0,...), (size1-1, size2-1,...)) list_of_association_pairs COBOL level-number type OCCURS size «TIMES». one-dimensional array definition... level-number type OCCURS min-size TO max-size «TIMES» DEPENDING «ON» size.[e] —N/a ^a In most expressions (except the sizeof and & operators), values of array types in C are automatically converted to a pointer of its first argument. See C syntax#Arrays for further details of syntax and pointer operations. ^b The C-like type x[] works in Ja, however type[] x is the preferred form of array declaration. ^c Subranges are used to define the bounds of the array. ^d JaScript's array are a special kind of object. ^e The DEPENDING ON clause in COBOL does not create a true variable length array and will always allocate the maximum size of the array. Other types[edit] Simple composite types Algebraic data types Unions Records Tuple expression Ada[1] type name is «abstract» «tagged» «limited» [record  field1 : type;  field2 : type;  ...end record | null record] N/A Any combination of records, unions, and enumerations (as well as references to those, enabling recursive types). type name (variation : discrete_type) is record  case variation is     when choice_list1 =>      fieldname1 : type;      ...     when choice_list2 =>      fieldname2 : type;      ...     ...  end case;end record ALGOL 68 struct (modename «fieldname», ...); Required types and operators can be user-defined union (modename, ...); C (C99) struct «name» {type name;...}; N/A N/A union {type name;...}; Objective-C C++ struct «name» {type name;...};[b] «std::»tuple C# struct name {type name;...} (val1, val2, ... ) N/A Ja N/A[a] JaScript N/A D struct name {type name;...} std.variant.Algebraic!(type,...) union {type name;...} Go struct {   «name» type  ...} Rust struct name {name: type, ...} (val1, val2, ... ) enum name { Foo(types), ...} union name {name: type, ...} Swift struct name {  var name «: type»  ...} («name1:» val1, «name2:» val2, «name3:» val3, ... ) enum name { case Foo«(types)» case Bar «(types)» ... } Common Lisp (defstruct name slot-name (slot-name initial-value) (slot-name initial-value :type type) ...) (cons val1 val2)[c] Scheme N/A ISLISP Pascal record  name: type;  ...end N/A N/A record  case type of  value: (types);  ...end Visual Basic Visual Basic .NET Structure name  Dim name As type  ...End Structure (val1, val2, ... ) Python N/A[a] «(»val1, val2, val3, ... «)» N/A S-Lang struct {name [=value], ...} Fortran TYPE name  type :: name  ...END TYPE PHP N/A[a] Perl N/A[d] N/A Raku N/A[a] Ruby OpenStruct.new({:name => value}) Scala case class name(«var» name: type, ...) (val1, val2, val3, ... ) abstract class name  case class Foo(«parameters») extends name  case class Bar(«parameters») extends name  ...orabstract class name  case object Foo extends name  case object Bar extends name  ...or a combination of case classes and case objects Windows PowerShell OCaml type name = {«mutable» name : type;...} «(»val1, val2, val3, ... «)» type name = Foo «of type» | Bar «of type» | ... N/A F# Standard ML type name = {name : type,...} (val1, val2, val3, ... ) datatype name = Foo «of type» | Bar «of type» | ... Haskell data Name = Constr {name :: type,...} data Name = Foo «types» | Bar «types» | ... COBOL level-number name type clauses.  level-number+n name type clauses.  ... N/A N/A name REDEFINES variable type. ^a Only classes are supported. ^b structs in C++ are actually classes, but he 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 he records, because Perl's type system allows different data types to be in an array, "hashes" (associative arrays) that don't he a variable index would effectively be the same as records. ^e Enumerations in this language are algebraic types with only nullary constructors Variable and constant declarations[edit] variable constant type synonym Ada[1] identifier : type« := initial_value»[e] identifier : constant type := final_value subtype identifier is type ALGOL 68 modename name« := initial_value»; modename name = value; mode synonym = modename; C (C99) type name« = initial_value»; enum{ name = value }; typedef type synonym; Objective-C C++ const type name = value; C# type name1« = initial_value», name2« = initial_value», ...;orvar name = initial_value; const type name = value, name = value, ...;orreadonly type name = value, name = value, ... ; using synonym = type; D type name« = initial_value»;orauto name = value; const type name = value;orimmutable type name = value; alias type synonym; Ja type name« = initial_value»; final type name = value; —N/a JaScript var name« = initial_value»; orlet name« = initial_value»; (since ECMAScript 2015) const name = value; (since ECMAScript 2015) Go var name type« = initial_value»orname := initial_value const name «type» = value type synonym type Racket (define name expression) Rust[f] let mut name«: type»« = initial_value»;static mut NAME: type = value; let name«: type»« = initial_value»;const NAME: type = value;static NAME: type = value; type synonym = typename; Swift var name «: type»« = initial_value» let name «: type» = value typealias synonym = type Common Lisp (defparameter name initial-value)or(defvar name initial-value) (defconstant name value) (deftype synonym () 'type) Scheme (define name initial_value) ISLISP (defglobal name initial_value)or(defdynamic name initial_value) (defconstant name value) —N/a Pascal[a] name: type« = initial_value» name = value synonym = type Visual Basic Dim name «As type» See notes to left.

Constants use the same syntax, and:

use Const instead of Dim he a restriction to only certain primitive typesConst name1 «As type» = value, name2 «As type» = value, ... Visual Basic .NET[10] The variable declaration syntax of VB.NET is unusually difficult to precisely describe.

Given that there exist the identifier suffixes ("modifiers"):

type_character, ailable as an alternative to an As clause for some primitive data types; nullable_specifier; and array_specifier;

and that

a modified_identifier is of the form identifier«type_character»«nullable_specifier»«array_specifier»; a modified_identifier_list is a comma-separated list of two or more occurrences of modified_identifier; and a declarator_list is a comma-separated list of declarators, which can be of the form identifier As object_creation_expression (object initializer declarator), modified_identifier «As non_array_type«array_rank_specifier»»« = initial_value» (single declarator), or modified_identifier_list «As «non_array_type««array_rank_specifier»» (multiple declarator);

valid declaration statements are of the form      Dim declarator_list, where, for the purpose of semantic analysis, to convert the declarator_list to a list of only single declarators:

The As clauses of each multiple declarator is distributed over its modified_identifier_list The As New type... of each object initializer declarator is replaced with As type = New type...

and for which, for each identifier,

a type_character and As clause do not both appear; if an As clause is present, an array_rank_specifier does not appear both as a modification of the identifier and on the type of the As clause; an unmodified_type can be determined, by the rule that, if a type_character or As clause is present, unmodified_type is that specified by such construct, and that otherwise, either Option Infer must be on and the identifier must he an initializer, in which case unmodified_type is that of the initializer, or Option Strict must be off, in which case unmodified_type is Object; its final_type is its unmodified_type prepended before its modifiers; its final_type is a valid type; and if an initial_value is present, either Option Strict is on and initial_value has a widening conversion to final_type, or Option Strict is off and initial_value has a narrowing conversion to final_type.

If Option Explicit is off, variables do not require explicit declaration; they are declared implicitly when used: name = initial_value

Imports synonym = type Xojo Dim name «As type»« = initial_value» —N/a Python name«: type» = initial_value —N/a synonym = type[b] CoffeeScript name = initial_value S-Lang name = initial_value; typedef struct {...} typename Fortran type :: name type, PARAMETER :: name = value PHP $name = initial_value; define("name", value);const name = value (5.3+) —N/a Perl «my» $name« = initial_value»;[c] use constant name => value; Raku «my «type»» $name« = initial_value»;[c] «my «type»» constant name = value; ::synonym ::= type Ruby name = initial_value Name = value synonym = type[b] Scala var name«: type» = initial_value val name«: type» = value type synonym = type Windows PowerShell «[type]» $name = initial_value —N/a —N/a Bash shell name=initial_value —N/a —N/a 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 COBOL level-number name type clauses. «0»1 name CONSTANT «AS» value. level-number name type clauses «IS» TYPEDEF. Mathematica name=initial_value —N/a —N/a ^a Pascal has declaration blocks. See functions. ^b Types are just regular objects, so you can just assign them. ^c In Perl, the "my" keyword scopes the variable into the block. ^d Technically, this does not declare name to be a mutable variable—in ML, all names can only be bound once; rather, it declares name to point to a "reference" data structure, which is a simple mutable cell. The data structure can then be read and written to using the ! and := operators, respectively. ^e If no initial value is given, an invalid value is automatically assigned (which will trigger a run-time exception if it used before a valid value has been assigned). While this behiour can be suppressed it is recommended in the interest of predictability. If no invalid value can be found for a type (for example in case of an unconstraint integer type), a valid, yet predictable value is chosen instead. ^f In Rust, if no initial value is given to a let or let mut variable and it is never assigned to later, there is an "unused variable" warning. If no value is provided for a const or static or static mut variable, there is an error. There is a "non-upper-case globals" error for non-uppercase const variables. After it is defined, a static mut variable can only be assigned to in an unsafe block or function. Control flow[edit] Conditional statements[edit] if else if select case conditional expression Ada[1] if condition then  statements«else  statements»end if if condition1 then  statementselsif condition2 then  statements...«else  statements»end if case expression is  when value_list1 => statements  when value_list2 => statements  ...  «when others => statements»end case (if condition1 then  expression1«elsif condition2 then  expression2»...else  expressionn)or(case expression is  when value_list1 => expression1  when value_list2 => expression2  ...  «when others => expressionn») Seed7 if condition then  statements«else  statements»end if if condition1 then  statementselsif condition2 then  statements...«else  statements»end if case expression of  when set1 : statements  ...  «otherwise: statements»end case Modula-2 if condition then  statements«else  statements»end if condition1 then  statementselsif condition2 then  statements...«else  statements»end case expression of  caseLabelList : statements |  ...  «else statements»end ALGOL 68 if condition then statements «else statements» fi if condition then statements elif condition then statements fi case switch in statements, statements«,... out statements» esac ( condition | valueIfTrue | valueIfFalse ) ALGOL 68(brief form) ( condition | statements «| statements» ) ( condition | statements |: condition | statements ) ( variable | statements,... «| statements» ) APL :If condition  instructions«:Else  instructions»:EndIf :If condition  instructions:ElseIf condition  instructions...«:Else  instructions»:EndIf :Select expression  :Case case1     instructions  ...  «:Else     instructions»:EndSelect {condition:valueIfTrue ⋄ valueIfFalse} C (C99) if (condition) instructions«else instructions»instructions can be a single statement or a block in the form of: { statements } if (condition) instructionselse if (condition) instructions...«else instructions»orif (condition) instructionselse { if (condition) instructions } switch (variable) {   case case1: instructions «; break;»  ...  «default: instructions»} condition ? valueIfTrue : valueIfFalse Objective-C C++ (STL) D Ja JaScript PHP C# if (condition) instructions«else instructions»

instructions can be a single statement or a block in the form of: { statements }

if (condition) instructionselse if (condition) instructions...«else instructions» switch (variable){   case case1:     instructions     «break_or_jump_statement»  ...  «default:     instructions     break_or_jump_statement»}

All non-empty cases must end with a break or goto case statement (that is, they are not allowed to fall-through to the next case). The default case is not required to come last.

condition ? valueIfTrue : valueIfFalse Windows PowerShell if (condition) instruction«else instructions» if (condition) { instructions }elseif (condition) { instructions }...«else { instructions }» switch (variable) { case1{instructions «break;» } ... «default { instructions }»} Go if condition {instructions}«else {instructions}» if condition {instructions}else if condition {instructions}...«else {instructions}»orswitch {   case condition: instructions  ...  «default: instructions»} switch variable {   case case1: instructions  ...  «default: instructions»} Swift if condition {instructions}«else {instructions}» if condition {instructions}else if condition {instructions}...«else {instructions}» switch variable {   case case1: instructions  ...  «default: instructions»} Perl if (condition) {instructions}«else {instructions}»orunless (notcondition) {instructions}«else {instructions}» if (condition) {instructions}elsif (condition) {instructions}...«else {instructions}»orunless (notcondition) {instructions}elsif (condition) {instructions}...«else {instructions}» use feature "switch";...given (variable) {   when (case1) { instructions }  ...  «default { instructions }»} condition ? valueIfTrue : valueIfFalse Racket (when testexpression expressions)or(unless condition expressions) (cond [testexpression expressions] [testexpression expressions] ... [else expressions]) (case expression [(case1) expressions] [(case2) expressions] ... [else expressions]) (if testexpression expressioniftrue expressioniffalse) Raku if condition {instructions}«else {instructions}»orunless notcondition {instructions} if condition {instructions}elsif condition {instructions}...«else {instructions} given variable {   when case1 { instructions }  ...  «default { instructions }»} condition ?? valueIfTrue !! valueIfFalse Ruby if condition  instructions«else  instructions» if condition  instructionselsif condition  instructions...«else  instructions»end case variable  when case1     instructions  ...  «else     instructions»end condition ? valueIfTrue : valueIfFalse Scala if (condition) {instructions}«else {instructions}» if (condition) {instructions}else if (condition) {instructions}...«else {instructions}» expression match {   case pattern1 => expression  case pattern2 => expression  ...  «case _ => expression»}[b] if (condition) valueIfTrue else valueIfFalse Smalltalk condition ifTrue:  trueBlock«ifFalse:  falseBlock»end condition ifTrue: trueBlock ifFalse: falseBlock Common Lisp (when condition  instructions)or(unless condition  instructions)or(if condition  (progn instructions)  «(progn instructions)») (cond (condition1 instructions)  (condition2 instructions)  ...  «(t instructions)») (case expression  (case1 instructions)  (case2 instructions)  ...  «(otherwise instructions)») (if test then else)or(cond (test1 value1) (test2 value2) ...)) Scheme (when condition instructions)or(if condition (begin instructions) «(begin instructions)») (cond (condition1 instructions) (condition2 instructions) ... «(else instructions)») (case (variable) ((case1) instructions) ((case2) instructions) ... «(else instructions)») (if condition valueIfTrue valueIfFalse) ISLISP (if condition  (progn instructions)  «(progn instructions)») (cond (condition1 instructions)  (condition2 instructions)  ...  «(t instructions)») (case expression  (case1 instructions)  (case2 instructions)  ...  «(t instructions)») (if condition valueIfTrue valueIfFalse) Pascal if condition then begin  instructionsend«else begin  instructionsend»'[c] if condition then begin  instructionsendelse if condition then begin  instructionsend...«else begin  instructionsend»[c] case variable of  case1: instructions  ...  «else: instructions»end[c] Visual Basic If condition Then  instructions«Else  instructions»End IfSingle-line, when instructions are instruction1 : instruction2 : ...:If condition Then instructions «Else instructions» If condition Then  instructionsElseIf condition Then  instructions...«Else  instructions»End IfSingle-line:See note about C-like languages; the Else clause of a single-line If statement can contain another single-line If statement. Select« Case» variable  Case case_pattern1     instructions  ...  «Case Else     instructions»End Select IIf(condition, valueIfTrue, valueIfFalse) Visual Basic .NET If(condition, valueIfTrue, valueIfFalse) Xojo Python[a] if condition :Tab ↹instructions«else:Tab ↹instructions» if condition :Tab ↹instructionselif condition :Tab ↹instructions...«else:Tab ↹instructions» Python 3.10+:match variable:Tab ↹case case1:Tab ↹Tab ↹instructionsTab ↹case case2:Tab ↹Tab ↹instructions Python 2.5+:valueIfTrue if condition else valueIfFalse S-Lang if (condition) { instructions } «else { instructions }» if (condition) { instructions } else if (condition) { instructions } ... «else { instructions }» switch (variable) { case case1: instructions } { case case2: instructions } ... Fortran IF (condition) THEN  instructionsELSE  instructionsENDIF IF (condition) THEN  instructionsELSEIF (condition) THEN  instructions...ELSE  instructionsENDIF SELECT CASE(variable)  CASE (case1)     instructions  ...  CASE DEFAULT     instructionsEND SELECT Forth condition IF instructions « ELSE instructions» THEN condition IF instructions ELSE condition IF instructions THEN THEN value CASE  case OF instructions ENDOF  case OF instructions ENDOF     default instructionsENDCASE condition IF valueIfTrue ELSE valueIfFalse THEN OCaml if condition then begin instructions end «else begin instructions end» if condition then begin instructions end else if condition then begin instructions end ... «else begin instructions end» match value with   pattern1 -> expression  | pattern2 -> expression  ...  «| _ -> expression»[b] if condition then valueIfTrue else valueIfFalse F# Lightweight syntax mode:

Either on a single line or with indentation as shown below: if condition thenTab ↹instructions«elseTab ↹instructions»Verbose syntax mode:Same as Standard ML.

Lightweight syntax mode:Either on a single line or with indentation as shown below:if condition thenTab ↹instructionselif condition thenTab ↹instructions...«elseTab ↹instructions»Verbose syntax mode:Same as Standard ML. Standard ML if condition then «(»instructions «)»else «(» instructions «)» if condition then «(»instructions «)»else if condition then «(» instructions «)»...else «(» instructions «)» case value of  pattern1 => expression  | pattern2 => expression  ...  «| _ => expression»[b] Haskell (GHC) if condition then expression else expressionorwhen condition (do instructions)orunless notcondition (do instructions) result | condition = expression  | condition = expression  | otherwise = expression case value of {   pattern1 -> expression;  pattern2 -> expression;  ...  «_ -> expression»}[b] Bash shell if condition-command; then  expression«else  expression»fi if condition-command; then  expressionelif condition-command; then  expression«else  expression»fi case "$variable" in  "$condition1" )     command...  "$condition2" )     command...esac CoffeeScript if condition then expression «else expression»orif condition  expression«else  expression»orexpression if conditionorunless condition  expression«else  expression»orexpression unless condition if condition then expression else if condition then expression «else expression»orif condition  expressionelse if condition  expression«else  expression»orunless condition  expressionelse unless condition  expression«else  expression» switch expression  when condition then expression  else expressionorswitch expression  when condition     expression  «else     expression» All conditions are expressions. COBOL IF condition «THEN»  expression«ELSE  expression».[d] EVALUATE expression «ALSO expression...»  WHEN case-or-condition «ALSO case-or-condition...»     expression  ...  «WHEN OTHER     expression»END-EVALUATE Rust if condition {   expression}« else {   expression}» if condition {   expression} else if condition {  expression}« else {  expression}» match variable {   pattern1 => expression,  pattern2 => expression,  pattern3 => expression,  «_ => expression»}[b][e] All conditions are expressions if else if select case conditional expression ^a A single instruction can be written on the same line following the colon. Multiple instructions are grouped together in a block which starts on a newline (The indentation is required). The conditional expression syntax does not follow this rule. ^b This is pattern matching and is similar to select case but not the same. It is usually used to deconstruct algebraic data types. ^c In languages of the Pascal family, the semicolon is not part of the statement. It is a separator between statements, not a terminator. ^d END-IF may be used instead of the period at the end. ^e In Rust, the comma (,) at the end of a match arm can be omitted after the last match arm, or after any match arm in which the expression is a block (ends in possibly empty matching brackets {}). Loop statements[edit] while loop do while loop (count-controlled) for loop foreach Ada[1] while condition loop  statementsend loop loop  statements  exit when not conditionend loop for index in «reverse» [first .. last | discrete_type] loop  statementsend loop for item of «reverse» iterator loop  statementsend loopor(for [all | some] [in | of] [first .. last | discrete_type | iterator] => predicate)[b] ALGOL 68 «for index» «from first» «by increment» «to last» «while condition» do statements od for key «to upb list» do «typename val=list[key];» statements od «while condition»  do statements od «while statements; condition»  do statements od «for index» «from first» «by increment» «to last» do statements od APL :While condition  statements:EndWhile :Repeat  statements:Until condition :For var«s» :In list  statements:EndFor :For var«s» :InEach list  statements:EndFor C (C99) instructions can be a single statement or a block in the form of: { statements }while (condition) instructions do instructions while (condition); for («type» i = first; i instructions) arrayorapp (fn item => instructions) list Haskell (GHC) —N/a Control.Monad.forM_ [first..last] (\i -> do instructions) Control.Monad.forM_list (\item -> do instructions) Eiffel from  setupuntil  conditionloop  instructionsend CoffeeScript while condition  expressionorexpression while conditionorwhile condition then expressionoruntil condition  expressionorexpression until conditionoruntil expression then condition —N/a for i in [first..last]  expressionorfor i in [first..last] then expressionorexpression for i in [first..last] for item in set  expressionorfor item in set then expressionorexpression for item in set COBOL PERFORM procedure-1 «THROUGH procedure-2» ««WITH» TEST BEFORE» UNTIL condition[c]orPERFORM ««WITH» TEST BEFORE» UNTIL condition  expressionEND-PERFORM PERFORM procedure-1 «THROUGH procedure-2» «WITH» TEST AFTER UNTIL condition[c]orPERFORM «WITH» TEST AFTER UNTIL condition  expressionEND-PERFORM PERFORM procedure-1 «THROUGH procedure-2» VARYING i FROM first BY increment UNTIL i > last[d]orPERFORM VARYING i FROM first BY increment UNTIL i > last  expressionEND-PERFORM[d] —N/a Rust while condition {   expression} loop {   expression     if condition {       break;  }} for i in first..last+1 {   expression}orfor i in first..=last {   expression} for item in set {   expression}[e]orset.into_iter().for_each(|item| expression);[e] ^a "step n" is used to change the loop interval. If "step" is omitted, then the loop interval is 1. ^b This implements the universal quantifier ("for all" or ∀) as well as the existential quantifier ("there exists" or ∃). ^c THRU may be used instead of THROUGH. ^d «IS» GREATER «THAN» may be used instead of >. ^e Type of set expression must implement trait std::iter::IntoIterator. Exceptions[edit] Further information: Exception handling syntax throw handler assertion Ada[1] raise exception_name «with string_expression» begin  statementsexception  when exception_list1 => statements;  when exception_list2 => statements;...  «when others => statements;»end[b] pragma Assert («Check =>» boolean_expression ««Message =>» string_expression»)[function | procedure | entry] with  Pre => boolean_expression  Post => boolean_expressionany_type with Type_Invariant => boolean_expression APL «string_expression» ⎕SIGNAL number_expression :Trap number«s»_expression  statements«:Case number«s»_expression  statements»...«:Else number«s»_expression  statements»:EndTrap «string_expression» ⎕SIGNAL 98/⍨~condition C (C99) longjmp(state, exception); switch (setjmp(state)) { case 0: instructions break; case exception: instructions ... } assert(condition); C++ throw exception; try { instructions } catch «(exception)» { instructions } ... C# try { instructions } catch «(exception« name»)» { instructions } ... «finally { instructions }» System.Diagnostics.Debug.Assert(condition);orSystem.Diagnostics.Trace.Assert(condition); Ja try { instructions } catch (exception) { instructions } ... «finally { instructions }» assert condition «: description»; JaScript try { instructions } catch (exception) { instructions} «finally { instructions }» ? D try { instructions } catch (exception) { instructions } ... «finally { instructions }» assert(condition); PHP try { instructions } catch (exception) { instructions } ... «finally { instructions }» assert(condition); S-Lang try { instructions } catch «exception» { instructions } ... «finally { instructions }» ? Windows PowerShell trap «[exception]» { instructions } ... instructionsortry { instructions } catch «[exception]» { instructions } ... «finally { instructions }» [Debug]::Assert(condition) Objective-C @throw exception; @try { instructions } @catch (exception) { instructions } ... «@finally { instructions }» NSAssert(condition, description); Swift throw exception (2.x) do { try expression ... instructions } catch exception { instructions } ... (2.x) assert(condition«, description») Perl die exception; eval { instructions }; if ($@) { instructions } ? Raku try { instructions CATCH { when exception { instructions } ...}} ? Ruby raise exception begin  instructionsrescue exception  instructions...«else  instructions»«ensure  instructions»end Smalltalk exception raise instructionBlock on: exception do: handlerBlock assert: conditionBlock Common Lisp (error "exception")or(error  type  arguments)or(error (make-condition  type  arguments)) (handler-case  (progn instructions)  (exception instructions)  ...)or(handler-bind  (condition     (lambda     instructions     «invoke-restart restart args»))...)[a] (assert condition)or(assert condition  «(place)  «error»»)or(check-type var type) Scheme (R6RS) (raise exception) (guard (con (condition instructions) ...) instructions) ? ISLISP (error "error-string" objects)or(signal-condition condition continuable) (with-handler  handler form*) ? Pascal raise Exception.Create() try Except on E: exception do begin instructions end; end; ? Visual Basic Err.Raise ERRORNUMBER With New Try: On Error Resume Next  OneInstruction.Catch: On Error GoTo 0: Select Case .Number  Case SOME_ERRORNUMBER     instructionsEnd Select: End With'*** Try class *** Private mstrDescription As String Private mlngNumber As Long Public Sub Catch() mstrDescription = Err.Description mlngNumber = Err.Number End Sub Public Property Get Number() As Long Number = mlngNumber End Property Public Property Get Description() As String Description = mstrDescription End Property [12] Debug.Assert condition Visual Basic .NET Throw exceptionorError errorcode Try  instructionsCatch« name As exception»« When condition»  instructions...«Finally  instructions»End Try System.Diagnostics.Debug.Assert(condition)orSystem.Diagnostics.Trace.Assert(condition) Xojo Raise exception Try  instructionsCatch «exception»  instructions...«Finally  instructions»End Try —N/a Python raise exception try:Tab ↹instructionsexcept «exception»:Tab ↹instructions...«else:Tab ↹instructions»«finally:Tab ↹instructions» assert condition Fortran —N/a Forth code THROW xt CATCH ( code or 0 ) —N/a OCaml raise exception try expression with pattern -> expression ... assert condition F# try expression with pattern -> expression ...ortry expression finally expression Standard ML raise exception «arg» expression handle pattern => expression ... Haskell (GHC) throw exceptionorthrowError expression catch tryExpression catchExpressionorcatchError tryExpression catchExpression assert condition expression COBOL RAISE «EXCEPTION» exception USE «AFTER» EXCEPTION OBJECT class-name.orUSE «AFTER» EO class-name.orUSE «AFTER» EXCEPTION CONDITION exception-name «FILE file-name».orUSE «AFTER» EC exception-name «FILE file-name». —N/a Rust No[13] assert!(condition) ^a Common Lisp allows with-simple-restart, restart-case and restart-bind to define restarts for use with invoke-restart. Unhandled conditions may cause the implementation to show a restarts menu to the user before unwinding the stack. ^b Uncaught exceptions are propagated to the innermost dynamically enclosing execution. Exceptions are not propagated across tasks (unless these tasks are currently synchronised in a rendezvous). Other control flow statements[edit] exit block (break) continue label branch (goto) return value from generator Ada[1] exit «loop_name» «when condition» —N/a label: goto label —N/a ALGOL 68 value exit; ... do statements; skip exit; label: statements od label: ... go to label; ...goto label; ...label; ... yield(value)

(Callback)[14]

APL :Lee :Continue label: →labelor:GoTo label —N/a C (C99) break; continue; label: goto label; —N/a Objective-C C++ (STL) D C# yield return value; Ja break «label»; continue «label»; —N/a JaScript yield value«;» PHP break «levels»; continue «levels»; goto label; yield «key =>» value; Perl last «label»; next «label»; Raku Go break «label» continue «label» goto label Swift break «label» continue «label» —N/a Bash shell break «levels» continue «levels» —N/a —N/a —N/a 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/a label:[a] goto label; —N/a Pascal (FPC) break; continue; Visual Basic Exit blockAlternatively, for methods,Return —N/a label: GoTo label Xojo Continue block Visual Basic .NET Yield value Python break continue —N/a yield value RPG IV LEE; ITER; S-Lang break; continue; Fortran EXIT CYCLE label[b] GOTO label —N/a Ruby break next Windows PowerShell break «label» continue OCaml —N/a F# Standard ML Haskell (GHC) COBOL EXIT PERFORM or EXIT PARAGRAPH or EXIT SECTION or EXIT. EXIT PERFORM CYCLE label «SECTION». GO TO label —N/a ^a Pascal has declaration blocks. See functions. ^b label must be a number between 1 and 99999. Functions[edit]

See reflective programming for calling and declaring functions by strings.

calling a function basic/void function value-returning function required main function Ada[1] foo «(parameters)» procedure foo «(parameters)» is begin statements end foo function foo «(parameters)» return type is begin statements end foo —N/a ALGOL 68 foo «(parameters)»; proc foo = «(parameters)» void: ( instructions ); proc foo = «(parameters)» rettype: ( instructions ...; retvalue ); —N/a APL «parameters» foo parameters foo←{ statements } foo←{ statements } —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) Ja public static void main(String[] args) { instructions }orpublic static void main(String... args) { instructions } D int main(«char[][] args») { instructions}orint main(«string[] args») { instructions}orvoid main(«char[][] args») { instructions}orvoid main(«string[] args») { instructions} C# Same as above; alternatively, if only one statement:

void foo(«parameters») => statement;

Same as above; alternatively, if simple enough to be an expression:

void foo(«parameters») => expression;

static void Main(«string[] args») method_bodyMay instead return int.(starting with C# 7.1:) May return Task or Task, and if so, may be async. JaScript function foo(«parameters») { instructions }orvar foo = function («parameters») { instructions }orvar foo = new Function ("«parameter»", ..., "«last parameter»" "instructions"); function foo(«parameters») { instructions ... return value; } —N/a Go func foo(«parameters») { instructions } func foo(«parameters») type { instructions ... return value } func main() { instructions } Swift func foo(«parameters») { instructions } func foo(«parameters») -> type { instructions ... return value } —N/a Common Lisp (foo «parameters») (defun foo («parameters»)  instructions)or(setf (symbol-function 'symbol)  function) (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) Pascal foo«(parameters)» procedure foo«(parameters)»; «forward;»[a]«label  label declarations»«const  constant declarations»«type  type declarations»«var  variable declarations»«local function declarations»begin  instructionsend; function foo«(parameters)»: type; «forward;»[a]«label  label declarations»«const  constant declarations»«type  type declarations»«var  variable declarations»«local function declarations»begin  instructions;  foo := valueend; program name;«label  label declarations»«const  constant declarations»«type  type declarations»«var  variable declarations»«function declarations»begin  instructionsend. Visual Basic Foo(«parameters») Sub Foo«(parameters)»  instructionsEnd Sub Function Foo«(parameters)»« As type»  instructions  Foo = valueEnd Function Sub Main()  instructionsEnd Sub Visual Basic .NET Same as above; alternatively:

Function Foo«(parameters)»« As type»  instructions  Return valueEnd FunctionThe As clause is not required if Option Strict is off. A type character may be used instead of the As clause.If control exits the function without a return value hing been explicitly specified, the function returns the default value for the return type.

Sub Main(««ByVal »args() As String»)  instructionsEnd SuborFunction Main(««ByVal »args() As String») As Integer  instructionsEnd Function Xojo Python foo(«parameters») def foo(«parameters»):Tab ↹instructions def foo(«parameters»):Tab ↹instructionsTab ↹return value —N/a 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»)  instructionsEND SUBROUTINE[c] type FUNCTION foo («arguments»)  instructions  ...  foo = valueEND FUNCTION[c] PROGRAM main  instructionsEND PROGRAM Forth «parameters» FOO : FOO « stack effect comment: ( before -- ) »  instructions; : FOO « stack effect comment: ( before -- after ) »  instructions; —N/a PHP foo(«parameters») function foo(«parameters») { instructions } function foo(«parameters») { instructions ... return value; } —N/a Perl foo(«parameters»)or&foo«(parameters)» sub foo { «my (parameters) = @_;» instructions } sub foo { «my (parameters) = @_;» instructions... «return» value; } Raku foo(«parameters»)or&foo«(parameters)» «multi »sub foo(parameters) { instructions } «our «type» »«multi »sub foo(parameters) { instructions ... «return» value; } Ruby foo«(parameters)» def foo«(parameters)»  instructionsend def foo«(parameters)»  instructions  «return» valueend Rust foo(«parameters») fn foo(«parameters») { instructions } fn foo(«parameters») -> type { instructions } fn main() { instructions } Scala foo«(parameters)» def foo«(parameters)»«: Unit =» { instructions } def foo«(parameters)»«: type» = { instructions ... «return» value } def main(args: Array[String]) { instructions } Windows PowerShell foo «parameters» function foo { instructions };orfunction foo { «param(parameters)» instructions } function foo «(parameters)» { instructions ... return value };orfunction foo { «param(parameters)» instructions ... return value } —N/a Bash shell foo «parameters» function foo {  instructions}orfoo () {  instructions} function foo {  instructions  return «exit_code»}orfoo () {   instructions  return «exit_code»} parameters $n ($1, $2, $3, ...) $@ (all parameters) $# (the number of parameters) $0 (this function name) OCaml foo parameters let «rec» foo parameters = instructions let «rec» foo parameters = instructions... return_value F# [] let main args = instructions Standard ML fun foo parameters = ( instructions ) fun foo parameters = ( instructions... return_value ) Haskell foo parameters = doTab ↹instructions foo parameters = return_valueorfoo parameters = doTab ↹instructionsTab ↹return value «main :: IO ()»main = do instructions Eiffel foo («parameters») foo («parameters»)  require     preconditions  do     instructions  ensure     postconditions  end foo («parameters»): type  require     preconditions  do     instructions     Result := value  ensure     postconditions  end [b] CoffeeScript foo() foo = -> foo = -> value —N/a foo parameters foo = () -> foo = ( parameters ) -> value COBOL CALL "foo" «USING parameters»  «exception-handling»«END-CALL»[d] «IDENTIFICATION DIVISION.»PROGRAM-ID. foo.«other divisions...»PROCEDURE DIVISION «USING parameters».  instructions. «IDENTIFICATION DIVISION.»PROGRAM-ID/FUNCTION-ID. foo.«other divisions...»DATA DIVISION.«other sections...»LINKAGE SECTION.«parameter definitions...»variable-to-return definition«other sections...»PROCEDURE DIVISION «USING parameters» RETURNING variable-to-return.  instructions. —N/a «FUNCTION» foo«(«parameters»)» —N/a ^a Pascal requires "forward;" for forward declarations. ^b Eiffel allows the specification of an application's root class and feature. ^c In Fortran, function/subroutine parameters are called arguments (since PARAMETER is a language keyword); the CALL keyword is required for subroutines. ^d Instead of using "foo", a string variable may be used instead containing the same value. Type conversions[edit]

Where string is a signed decimal number:

string to integer string to long integer string to floating point integer to string floating point to string Ada[1] Integer'Value (string_expression) Long_Integer'Value (string_expression) Float'Value (string_expression) Integer'Image (integer_expression) Float'Image (float_expression) ALGOL 68 with general, and then specific formats With prior declarations and association of: string buf := "12345678.9012e34 "; file proxy; associate(proxy, buf); get(proxy, ivar); get(proxy, livar); get(proxy, rvar); put(proxy, ival); put(proxy, rval); getf(proxy, ($g$, ivar));orgetf(proxy, ($dddd$, ivar)); getf(proxy, ($g$, livar));orgetf(proxy, ($8d$, livar)); getf(proxy, ($g$, rvar));orgetf(proxy, ($8d.4dE2d$, rvar)); putf(proxy, ($g$, ival));orputf(proxy, ($4d$, ival)); putf(proxy, ($g(width, places, exp)$, rval));orputf(proxy, ($8d.4dE2d$, rval)); APL ⍎string_expression ⍎string_expression ⍎string_expression ⍕integer_expression ⍕float_expression C (C99) integer = atoi(string); long = atol(string); float = atof(string); sprintf(string, "%i", integer); sprintf(string, "%f", float); Objective-C integer = [string intValue]; long = [string longLongValue]; float = [string doubleValue]; string = [NSString stringWithFormat:@"%i", integer]; string = [NSString stringWithFormat:@"%f", float]; C++ (STL) «std::»istringstream(string) >> number; «std::»ostringstream o; o number string)) (define string (number->string number)) ISLISP (setf integer (convert string )) (setf float (convert string )) (setf string (convert number )) Pascal integer := StrToInt(string); float := StrToFloat(string); string := IntToStr(integer); string := FloatToStr(float); Visual Basic integer = CInt(string) long = CLng(string) float = CSng(string)double = CDbl(string) string = CStr(number) Visual Basic .NET(can use both VB syntax above and .NET methods shown right) integer = Integer.Parse(string) long = Long.Parse(string) float = Single.Parse(string)double = Double.Parse(string) string = number.ToString() Xojo integer = Val(string) long = Val(string) double = Val(string)double = CDbl(string) string = CStr(number)orstring = Str(number) Python integer = int(string) long = long(string) float = float(string) string = str(number) S-Lang integer = atoi(string); long = atol(string); float = atof(string); string = string(number); Fortran READ(string,format) number WRITE(string,format) number PHP integer = intval(string);orinteger = (int)string; float = floatval(string);float = (float)string; string = "$number";orstring = strval(number);orstring = (string)number; Perl[b] number = 0 + string; string = "number"; Raku number = +string; string = ~number; Ruby integer = string.to_iorinteger = Integer(string) float = string.to_ffloat = Float(string) string = number.to_s Scala integer = string.toInt long = string.toLong float = string.toFloatdouble = string.toDouble string = number.toString Smalltalk integer := Integer readFrom: string float := Float readFrom: string string := number asString Windows PowerShell integer = [int]string long = [long]string float = [float]string string = [string]number;orstring = "number";orstring = (number).ToString() OCaml let integer = int_of_string string let float = float_of_string string let string = string_of_int integer let string = string_of_float float F# let integer = int string let integer = int64 string let float = float string let string = string number Standard ML val integer = Int.fromString string val float = Real.fromString string val string = Int.toString integer val string = Real.toString float Haskell (GHC) number = read string string = show number COBOL MOVE «FUNCTION» NUMVAL(string)[c] TO number MOVE number TO numeric-edited ^a JaScript only uses floating point numbers so there are some technicalities.[7] ^b Perl doesn't he separate types. Strings and numbers are interchangeable. ^c NUMVAL-C or NUMVAL-F may be used instead of NUMVAL. ^ str::parse is ailable to convert any type that has an implementation of the std::str::FromStr trait. Both str::parse and FromStr::from_str return a Result that contains the specified type if there is no error. The turbofish (::) on str::parse can be omitted if the type can be inferred from context. Standard stream I/O[edit] read from write to stdin stdout stderr Ada[1] Get (x) Put (x) Put (Standard_Error, x) ALGOL 68 readf(($format$, x));orgetf(stand in, ($format$, x)); printf(($format$, x));orputf(stand out, ($format$, x)); putf(stand error, ($format$, x));[a] APL x←⎕ ⎕←x ⍞←x C (C99) scanf(format, &x);orfscanf(stdin, format, &x);[b] printf(format, x);orfprintf(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 ...) print_int xorprint_endline strorPrintf.printf format x ... prerr_int xorprerr_endline strorPrintf.eprintf format x ... F# let x = System.Console.ReadLine() printf format x ...orprintfn format x ... eprintf format x ...oreprintfn format x ... Standard ML val str = TextIO.inputLIne TextIO.stdIn print str TextIO.output (TextIO.stdErr, str) Haskell (GHC) x

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至lsinopec@gmail.com举报,一经查实,本站将立刻删除。

上一篇 没有了

下一篇没有了