This article needs additional citations for verification. (February 2009) |
Este artículo compara una gran cantidad de lenguajes de programación tabulando sus tipos de datos , su sintaxis de expresión , declaración y sentencia , y algunas interfaces comunes del sistema operativo.
En general, var , var o var es la forma en que se representan los nombres de las variables u otros valores no literales que el lector debe interpretar. El resto es código literal. Los guillemets ( «
y »
) encierran secciones opcionales. Tab ↹indica una sangría necesaria (espacio en blanco).
Las tablas no están ordenadas lexicográficamente en forma ascendente por nombre de lenguaje de programación de forma predeterminada, y algunos lenguajes tienen entradas en algunas tablas pero no en otras.
8 bits ( bytes ) | 16 bits ( entero corto ) | 32 bits | 64 bit ( entero largo ) | Tamaño de la palabra | Arbitrariamente preciso ( bignum ) | ||||||
---|---|---|---|---|---|---|---|---|---|---|---|
Firmado | No firmado | Firmado | No firmado | Firmado | No firmado | Firmado | No firmado | Firmado | No firmado | ||
Ada [1] | range -2**7 .. 2**7 - 1 [j] | range 0 .. 2**8 - 1 [j] o mod 2**8 [k] | range -2**15 .. 2**15 - 1 [j] | range 0 .. 2**16 - 1 [j] o mod 2**16 [k] | range -2**31 .. 2**31 - 1 [j] | range 0 .. 2**32 - 1 [j] o mod 2**32 [k] | range -2**63 .. 2**63 - 1 [j] | mod 2**64 [k] | Integer [j] | range 0 .. 2**Integer' [j] o [k]mod Integer' | — |
ALGOL 68 (ancho variable) | short short int [do] | — | short int [do] | — | int [do] | — | long int [do] | — | int [do] | — | long long int [a] [sol] |
bytes ybits | |||||||||||
C ( C99 ancho fijo) | int8_t | uint8_t | int16_t | uint16_t | int32_t | uint32_t | int64_t | uint64_t | intptr_t [do] | size_t [do] | — |
C++ ( C++11 de ancho fijo) | |||||||||||
C ( C99 ancho variable) | signed char | unsigned char | short [do] | unsigned short [do] | long [do] | unsigned long [do] | long long [do] | unsigned long long [do] | int [do] | unsigned int [do] | |
C++ ( ancho variable de C++11 ) | |||||||||||
Objetivo-C ( Cacao ) | signed char oint8_t | unsigned char ouint8_t | short oint16_t | unsigned short ouint16_t | int oint32_t | unsigned int ouint32_t | long long oint64_t | unsigned long long ouint64_t | NSInteger olong | NSUInteger ounsigned long | |
DO# | sbyte | byte | short | ushort | int | uint | long | ulong | IntPtr | UIntPtr | System.Numerics. (.NET 4.0) |
Java | byte | — | char [b] | — | — | — | — | java.math. | |||
Ir | int8 | uint8 obyte | int16 | uint16 | int32 | uint32 | int64 | uint64 | int | uint | big.Int |
Óxido | i8 | u8 | i16 | u16 | i32 | u32 | i64 | u64 | isize | usize | — |
Rápido | Int8 | UInt8 | Int16 | UInt16 | Int32 | UInt32 | Int64 | UInt64 | Int | UInt | |
D | byte | ubyte | short | ushort | int | uint | long | ulong | — | — | BigInt |
Lisp común [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 | ||
Esquema | |||||||||||
ISLISP [3] | bignum | ||||||||||
Pascal ( FPC ) | shortint | byte | smallint | word | longint | longword | int64 | qword | integer | cardinal | — |
Visual Basic | — | Byte | Integer | — | Long | — | — | — | — | ||
Visual Basic .NET | SByte | Short | UShort | Integer | UInteger | Long | ULong | System.Numerics (.NET 4.0) | |||
Libre básico | Byte oInteger<8> | UByte oUInteger<8> | Short oInteger<16> | UShort oUInteger<16> | Long oInteger<32> | ULong oUInteger<32> | LongInt oInteger<64> | ULongInt oUInteger<64> | Integer | UInteger | — |
Python 2.x | — | — | — | — | int | — | long | ||||
Python 3.x | — | — | — | — | — | int | |||||
Jerga | — | — | — | — | — | — | |||||
Fortran | INTEGER [F] | — | INTEGER [F] | — | INTEGER [F] | — | INTEGER [F] | — | |||
PHP | — | — | int [metro] | — | int [metro] | — | — | [mi] | |||
Perl 5 | - [d] | - [d] | - [d] | - [d] | - [d] | Math::BigInt | |||||
Raku | int8 | uint8 | int16 | uint16 | int32 | uint32 | int64 | uint64 | Int | — | |
Rubí | — | — | — | — | Fixnum | — | Bignum | ||||
Erlang [n] | — | — | — | — | integer() | — | integer() [el] | ||||
Escala | Byte | — | Short | Char [l] | Int | — | Long | — | — | — | scala.math.BigInt |
Semilla7 | — | — | — | — | — | — | integer | — | — | — | bigInteger |
Charla informal | — | — | — | — | SmallInteger [i] | — | LargeInteger [i] | ||||
Windows PowerShell | — | — | — | — | — | — | |||||
OCaml | — | — | int32 | — | int64 | — | int onativeint | open Big_int;; obig_int | |||
F# | sbyte | byte | int16 | uint16 | int32 oint | uint32 | uint64 | nativeint | unativeint | bigint | |
ML estándar | — | Word8.word | — | Int32.int | Word32.word | Int64.int | Word64.word | int | word | LargeInt.int oIntInf.int | |
Haskell ( GHC ) | «import Int» oInt8 | «import Word» oWord8 | «import Int» oInt16 | «import Word» oWord16 | «import Int» oInt32 | «import Word» oWord32 | «import Int» oInt64 | «import Word» oWord64 | Int | «import Word» oWord | Integer |
Torre Eiffel | INTEGER_8 | NATURAL_8 | INTEGER_16 | NATURAL_16 | INTEGER_32 | NATURAL_32 | INTEGER_64 | NATURAL_64 | INTEGER | NATURAL | — |
COBOL [h] | BINARY-CHAR «SIGNED» | BINARY-CHAR UNSIGNED | BINARY-SHORT «SIGNED» | BINARY-SHORT UNSIGNED | BINARY-LONG «SIGNED» | BINARY-LONG UNSIGNED | BINARY-DOUBLE «SIGNED» | BINARY-DOUBLE UNSIGNED | — | — | — |
Matemática | — | — | — | — | — | Integer | |||||
Lenguaje Wolfram | — | — | — | — | — | Integer |
int shorts
yint lengths
se pueden usar para determinar cuántasshort
s ylong
s se pueden anteponer de manera útil ashort int
ylong int
. Los tamaños reales deshort int
,int
, ylong int
están disponibles como constantesshort max int
,max int
, ylong max int
etc.short
,int
,long
, y ( C99 , C++11 )long long
, por lo que dependen de la implementación. En C y C++short
,long
, ylong long
tengan al menos 16, 32 y 64 bits de ancho, respectivamente, pero pueden tener más.int
Se requiere que el tipo tenga al menos el mismo ancho queshort
y como máximo el mismo ancho quelong
, y normalmente es el ancho del tamaño de palabra en el procesador de la máquina (es decir, en una máquina de 32 bits suele tener 32 bits de ancho; en máquinas de 64 bits a veces tiene 64 bits de ancho). C99 y C++11 [ cita requerida ] también definen los[u]intN_t
tipos de ancho exacto en elencabezado stdint.h . Consulte Sintaxis de C#Tipos integrales para obtener más información. Además, los tipossize_t
yptrdiff_t
se definen en relación con el tamaño de la dirección para contener números enteros con y sin signo suficientemente grandes para manejar índices de matriz y la diferencia entre punteros.n
lo proporciona laSELECTED_INT_KIND
función intrínseca [4] .--precision "number"
puede establecer la precisión delong long int
s en el "número" de dígitos significativos requeridos. Lasconstantes estándarlong long int width
ylong long max int
se pueden utilizar para determinar la precisión real.PIC S9999
", por ejemplo, requeriría una variable con signo de precisión de cuatro dígitos decimales. Si se especifica como un campo binario, se seleccionaría un tipo con signo de 16 bits en la mayoría de las plataformas.range 1 .. Integer'Last
) y Natural (range 0 .. Integer'Last
).Short_Short_Integer
(8 bits),Short_Integer
(16 bits) yLong_Integer
(64 bits) también suelen estar predefinidos, pero no son requeridos por el estándar de Ada. Las comprobaciones en tiempo de ejecución se pueden deshabilitar si el rendimiento es más importante que las comprobaciones de integridad.int
en PHP tiene el mismo ancho quelong
el tipo en C en ese sistema. [c]Precisión simple | Doble precisión | Otra precisión | Depende del procesador | |
---|---|---|---|---|
Ada [1] | Float | Long_Float | — | |
ALGOL 68 | real [a] | long real [a] | short real , long long real , etc. [d] | |
do | float [b] | double | long double [F] | |
C++ (STL) | ||||
Objetivo-C ( Cacao ) | CGFloat | |||
DO# | float | — | ||
Java | ||||
Ir | float32 | float64 | ||
Óxido | f32 | f64 | ||
Rápido | Float oFloat32 | Double oFloat64 | Float80 [gramo] | CGFloat |
D | float | double | real | |
Ceceo común | single-float | double-float | float, short-float, long-float | |
Esquema | ||||
ISLISP | ||||
Pascal ( FPC ) | single | double | real | |
Visual Basic | Single | Double | — | |
Visual Basic .NET | ||||
Xojo | ||||
Pitón | — | float | ||
JavaScript | Number [7] | — | ||
Jerga | ||||
Fortran | REAL(KIND = n) [do] | |||
PHP | float | |||
Perl | ||||
Raku | num32 | num64 | Num | |
Rubí | — | Float | — | |
Escala | Float | Double | ||
Semilla7 | — | float | ||
Charla informal | Float | Double | ||
Windows PowerShell | ||||
OCaml | — | float | — | |
F# | float32 | |||
ML estándar | — | real | ||
Haskell ( GHC ) | Float | Double | ||
Torre Eiffel | REAL_32 | REAL_64 | ||
COBOL | FLOAT-BINARY-7 [mi] | FLOAT-BINARY-34 [mi] | FLOAT-SHORT , FLOAT-LONG ,FLOAT-EXTENDED | |
Matemática | — | — | Real |
real shorts
yreal lengths
se pueden usar para determinar cuántasshort
s ylong
s se pueden anteponer de manera útil ashort real
ylong real
. Los tamaños reales deshort real
,real
, ylong real
están disponibles como las constantesshort max real
,max real
ylong max real
etc. Con las constantesshort small real
,small real
y disponibles para la máquina epsilonlong small real
de cada tipo.n
lo proporciona laSELECTED_REAL_KIND
función intrínseca [8] .--precision "number"
puede establecer la precisión delong long real
s en el "número" de dígitos significativos requeridos. Lasconstantes estándarlong long real width
ylong long max real
se pueden utilizar para determinar la precisión real.double
en muchas implementaciones.long double
en los lenguajes C.Entero | Precisión simple | Doble precisión | Precisión media y cuádruple, etc. | |
---|---|---|---|---|
Ada [1] | — | Complex [b] | Complex [b] | Complex [b] |
ALGOL 68 | — | compl | long compl etc. | short compl etc. y long long compl etc. |
C ( C99 ) [9] | — | float complex | double complex | — |
C++ (STL) | — | std::complex<float> | std::complex<double> | |
DO# | — | — | System.Numerics.Complex (.NET 4.0) | |
Java | — | — | — | |
Ir | — | complex64 | complex128 | |
D | — | cfloat | cdouble | |
Objetivo-C | — | — | — | |
Ceceo común | (entero complejo) | (flotante simple complejo) | (flotante doble complejo) | complejo |
Esquema | — | |||
Pascal | — | — | ||
Visual Basic | — | — | ||
Visual Basic .NET | — | — | System.Numerics.Complex (.NET 4.0) | |
Perl | Math::Complex | |||
Raku | complex64 | complex128 | Complex | |
Pitón | complex | — | ||
JavaScript | — | — | ||
Jerga | — | — | ||
Fortran | COMPLEX(KIND = n) [a] | |||
Rubí | Complex | — | Complex | |
Escala | — | — | — | |
Semilla7 | — | — | complex | |
Charla informal | Complex | Complex | Complex | |
Windows PowerShell | — | — | ||
OCaml | — | — | Complex.t | |
F# | System.Numerics.Complex (.NET 4.0) | |||
ML estándar | — | — | — | |
Haskell ( GHC ) | — | Complex.Complex Float | Complex.Complex Double | |
Torre Eiffel | — | — | — | |
COBOL | — | — | — | |
Matemática | Complex | — | — | Complex |
n
lo proporciona laSELECTED_REAL_KIND
función intrínseca [8] .Texto | Booleano | Enumeración | Objeto / Universal | ||
---|---|---|---|---|---|
Personaje | Cadena [a] | ||||
Ada [1] | Character | String , Bounded_String ,Unbounded_String | Boolean | (item1, item2, ...) | tagged null record |
ALGOL 68 | char | string ,bytes | bool ,bits | — - Definido por el usuario | — |
C ( C99 ) | char ,wchar_t | — | bool [b] | enum «name» { item1, item2, ... }; | void * |
C++ (STL) | «std::»string | ||||
Objetivo-C | unichar | NSString * | BOOL | id | |
DO# | char | string | bool | enum name { item1« = value», item2« = value», ... } | objeto |
Java | String | boolean | enum name { item1, item2, ... } | Object | |
Ir | byte ,rune | string | bool | const ( | interface{} |
Óxido | char | String | bool | enum name { item1« = value», item2« = value», ... } | std::any::Any |
Rápido | Character | String | Bool | enum name { case item1, item2, ... } | Any |
D | char | string | bool | enum name { item1, item2, ... } | std.variant.Variant |
Ceceo común | character | string | boolean | (member item1 item2 ...) | t |
Esquema | |||||
ISLISP | |||||
Pascal (ISO) | char | — | boolean | ( item1, item2, ... ) | — |
Objeto Pascal ( Delphi ) | string | variant | |||
Visual Basic | — | String | Boolean | Enum name | [[Variant type|Variant]] |
Visual Basic .NET | Char | Object | |||
Xojo | — | Object oVariant | |||
Pitón | - [d] | str | bool | from enum import Enum | object |
JavaScript | - [d] | String | Boolean | Object | |
Jerga | |||||
Fortran | CHARACTER(LEN = *) | CHARACTER(LEN = :), allocatable | LOGICAL(KIND = n) [F] | CLASS(*) | |
PHP | - [d] | string | bool | (se omite la declaración de tipo) | |
Perl | - [d] | UNIVERSAL | |||
Raku | Char | Str | Bool | enum name<item1 item2 ...> enum name <<:item1(value) :item2(value) ..>> | Mu |
Rubí | - [d] | String | Object [do] | Object | |
Escala | Char | String | Boolean | object name extends Enumeration { | Any |
Semilla7 | char | string | boolean | const type: name is new enum | |
Windows PowerShell | |||||
OCaml | char | string | bool | — [y] | — |
F# | type name = item1 = value |item2 = value | ... | obj | |||
ML estándar | — [y] | — | |||
Haskell ( GHC ) | Char | String | Bool | — [y] | — |
Torre Eiffel | CHARACTER | STRING | BOOLEAN | — | ANY |
COBOL | PIC X | PIC X(string length) oPIC X«X...» | PIC 1«(number of digits)» oPIC 1«1...» | — | OBJECT REFERENCE |
Matemática | - [d] | String | — |
TrueClass
se evalúa como verdadero y todo lo queFalseClass
se evalúa como falso.n
lo proporciona laSELECTED_INT_KIND
función intrínseca [4] .matriz de tamaño fijo | matriz de tamaño dinámico | |||
---|---|---|---|---|
matriz unidimensional | matriz multidimensional | matriz unidimensional | matriz multidimensional | |
Ada [1] | array (<first> .. <last>) of <type> o array (<discrete_type>) of <type> | array (<first1> .. <last1>, <first2> .. <last2>, ...) of <type> o array (<discrete_type1>, <discrete_type2>, ...) of <type> | array (<discrete_type> range <>) of <type> | array (<discrete_type1> range <>, <discrete_type2> range <>, ...) of <type> |
ALGOL 68 | [first:last] o simplemente: [size] | [first1:last1, first2:last2] o etc. [first1:last1][first2:last2] | flex[first:last] o simplemente: flex[size] | flex[first1:last1, first2:last2] o flex[first1:last1] |
C ( C99 ) | type name[size] [a] | type name[size1][size2] [a] | type *name o dentro de un bloque: int n = ...; type name[n] | |
C++ (STL) | «std::»array<type, size> (C++11) | «std::»vector<type> | ||
DO# | type[] | type[,,...] | System o System | |
Java | type[] [b] | type[][]... [b] | ArrayList or ArrayList<type> | |
D | type[size] | type[size1][size2] | type[] | |
Ir | [size]type | [size1][size2]...type | []type | [][]type |
Óxido | [type; size] | [[type; size1]; size2] | Vec<type> | Vec<Vec<type>> |
Rápido | [type] oArray<type> | [[type]] oArray<Array<type>> | ||
Objetivo-C | NSArray | NSMutableArray | ||
JavaScript | — | — | Array [d] | |
Ceceo común | (simple-array type (dimension)) | (simple-array type (dimension1 dimension2)) | (array type (dimension)) | (array type (dimension1 dimension2)) |
Esquema | ||||
ISLISP | ||||
Pascal | array[first..last] of type [do] | array[first1..last1] of array[first2..last2] ... of type [c]o [c] array[first1..last1, first2..last2, ...] of type | — | — |
Objeto 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 o System | |
Pitón | list | |||
Jerga | 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 | |||
Rubí | x = Array.new(size1){ Array.new(size2) } | Array | ||
Escala | Array[type] | Array[...[Array[type]]...] | ArrayBuffer[type] | |
Semilla7 | array type o array [idxType] type | array array type o array [idxType] array [idxType] type | array type o array [idxType] type | array array type o array [idxType] array [idxType] type |
Charla informal | Array | OrderedCollection | ||
Windows PowerShell | type[] | type[,,...] | ||
OCaml | type array | type array ... array | ||
F# | type [] o type array | type [,,...] | System o System | |
ML estándar | 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». | Definición de matriz unidimensional... | level-number type OCCURS min-size TO max-size «TIMES» DEPENDING «ON» size. [mi] | — |
sizeof
y&
), los valores de los tipos de matriz en C se convierten automáticamente en un puntero a su primer argumento. Consulte Sintaxis de C#Matrices para obtener más detalles sobre la sintaxis y las operaciones con punteros.type x[]
funciona en Java, sin embargotype[] x
es la forma preferida de declaración de matriz.DEPENDING ON
cláusula en COBOL no crea una verdadera matriz de longitud variable y siempre asignará el tamaño máximo de la matriz.Tipos compuestos simples | Tipos de datos algebraicos | Sindicatos | ||
---|---|---|---|---|
Archivos | Expresión de tupla | |||
Ada [1] | type name is «abstract» «tagged» «limited» [record | — | Cualquier combinación de registros, uniones y enumeraciones (así como referencias a ellos, habilitando tipos recursivos). | type name (variation : discrete_type) is record |
ALGOL 68 | struct (modename «fieldname», ...); | Los tipos y operadores requeridos pueden ser definidos por el usuario | union (modename, ...); | |
C ( C99 ) | struct «name» {type name;...}; | — | — | union {type name;...}; |
Objetivo-C | ||||
C++ | struct «name» {type name;...}; [b] | «std::»tuple<type1..typen> | ||
DO# | struct name {type name;...} | (val1, val2, ... ) | — | |
Java | - [a] | |||
JavaScript | — | |||
D | struct name {type name;...} | std.variant.Algebraic!(type,...) | union {type name;...} | |
Ir | struct { | |||
Óxido | struct name {name: type, ...} | (val1, val2, ... ) | enum name { Foo(types), ...} | union name {name: type, ...} |
Rápido | struct name { | («name1:» val1, «name2:» val2, «name3:» val3, ... ) | enum name { case Foo«(types)» case Bar «(types)» ... } | |
Ceceo común | (defstruct name slot-name (slot-name initial-value) (slot-name initial-value :type type) ...) | (cons val1 val2) [do] | ||
Esquema | — | |||
ISLISP | ||||
Pascal | record | — | — | record |
Visual Basic | ||||
Visual Basic .NET | Structure name | (val1, val2, ... ) | ||
Pitón | - [a] | «(»val1, val2, val3, ... «)» | — | |
Jerga | struct {name [=value], ...} | |||
Fortran | TYPE name | |||
PHP | - [a] | |||
Perl | - [d] | — | ||
Raku | - [a] | |||
Rubí | OpenStruct.new({:name => value}) | |||
Escala | case class name(«var» name: type, ...) | (val1, val2, val3, ... ) | abstract class name o una combinación de clases de casos y objetos de casos abstract class name | |
Windows PowerShell | ||||
OCaml | type name = {«mutable» name : type;...} | «(»val1, val2, val3, ... «)» | type name = Foo «of type» | Bar «of type» | ... | — |
F# | ||||
ML estándar | 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. | — | — | name REDEFINES variable type. |
struct
en C++ son en realidad clases, pero tienen visibilidad pública predeterminada ytambién son objetos POD . C++11 extendió esto aún más, para hacer que las clases actúen de manera idéntica a los objetos POD en muchos más casos.variable | constante | escribir sinónimo | |
---|---|---|---|
Ada [1] | identifier : type« := initial_value» [mi] | 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; |
Objetivo-C | |||
C++ | const type name = value; | ||
DO# | type name1« = initial_value», name2« = initial_value», ...; o var name = initial_value; | const type name = value, name = value, ...; o readonly type name = value, name = value, ... ; | using synonym = type; |
D | type name« = initial_value»; o auto name = value; | const type name = value; o immutable type name = value; | alias type synonym; |
Java | type name« = initial_value»; | final type name = value; | — |
JavaScript | var name« = initial_value»; o (desde ECMAScript 2015)let name« = initial_value»; | const name = value; (desde ECMAScript 2015) | |
Ir | var name type« = initial_value» o name := initial_value | const name «type» = value | type synonym type |
Óxido [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; |
Rápido | var name «: type»« = initial_value» | let name «: type» = value | typealias synonym = type |
Ceceo común | (defparameter name initial-value) o (defvar name initial-value) | (defconstant name value) | (deftype synonym () 'type) |
Esquema | (define name initial_value) | ||
ISLISP | (defglobal name initial_value) o (defdynamic name initial_value) | (defconstant name value) | — |
Pascual [a] | name: type« = initial_value» | name = value | synonym = type |
Visual Basic | Dim name «As type» | Ver notas a la izquierda. Las constantes utilizan la misma sintaxis y:
| |
Visual Basic .NET [10] | La sintaxis de declaración de variables de VB.NET es inusualmente difícil de describir con precisión. Dado que existen los sufijos identificadores ("modificadores"):
Y eso
Las declaraciones válidas tienen la forma
, donde, a los efectos del análisis semántico, para convertirlas en una lista de declaradores únicos:
y para lo cual, para cada
Si | Imports synonym = type | |
Xojo | Dim name «As type»« = initial_value» | — | |
Pitón | name«: type» = initial_value | — | synonym = type [b] |
Script de café | name = initial_value | ||
Jerga | name = initial_value; | typedef struct {...} typename | |
Fortran | type :: name | type, PARAMETER :: name = value | |
PHP | $name = initial_value; | define("name", value); | — |
Perl | «my» $name« = initial_value»; [do] | use constant name => value; | |
Raku | «my «type»» $name« = initial_value»; [do] | «my «type»» constant name = value; | ::synonym ::= type |
Rubí | name = initial_value | Name = value | synonym = type [b] |
Escala | var name«: type» = initial_value | val name«: type» = value | type synonym = type |
Windows PowerShell | «[type]» $name = initial_value | — | — |
Concha bash | name=initial_value | — | — |
OCaml | let name« : type ref» = ref value [d] | let name «: type» = value | type synonym = type |
F# | let mutable name «: type» = value | ||
ML estándar | val name «: type ref» = ref value [d] | val name «: type» = value | |
Haskell | «name::type;» name = value | type Synonym = type | |
Adelante | VARIABLE name (en algunos sistemas utilizar en su lugar)value VARIABLE name | value CONSTANT name | |
COBOL | level-number name type clauses. | «0»1 name CONSTANT «AS» value. | level-number name type clauses «IS» TYPEDEF. |
Matemática | name=initial_value | — | — |
!
y:=
, respectivamente.let
olet mut
y nunca se le asigna más adelante, aparece una advertencia de "variable no utilizada". Si no se proporciona ningún valor para unaconst
ostatic
ostatic mut
, aparece un error. Aparece un error de "variables globales sin mayúsculas" paraconst
las variables sin mayúsculas. Una vez definida,static mut
solo se puede asignar una variable en ununsafe
bloque o función.si | De lo contrario si | seleccionar caso | expresión condicional | |
---|---|---|---|---|
Ada [1] | if condition then | if condition1 then | case expression is | (if condition1 then o (case expression is |
Semilla7 | if condition then | if condition1 then | case expression of | |
Módulo-2 | if condition then | if condition1 then | case expression of | |
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 (forma abreviada) | ( condition | statements «| statements» ) | ( condition | statements |: condition | statements ) | ( variable | statements,... «| statements» ) | |
APL | :If condition | :If condition | :Select expression | {condition:valueIfTrue ⋄ valueIfFalse} |
C ( C99 ) | if (condition) instructions instructions Puede ser una sola declaración o un bloque en forma de:{ statements } | if (condition) instructions o if (condition) instructions | switch (variable) { | condition ? valueIfTrue : valueIfFalse |
Objetivo-C | ||||
C++ (STL) | ||||
D | ||||
Java | ||||
JavaScript | ||||
PHP | ||||
DO# | if (condition) instructions
| if (condition) instructions | switch (variable) Todos los casos no vacíos deben terminar con una instrucción | condition ? valueIfTrue : valueIfFalse |
Windows PowerShell | if (condition) instruction | if (condition) { instructions } | switch (variable) { case1{instructions «break;» } ... «default { instructions }»} | |
Ir | if condition {instructions} | if condition {instructions} o switch { | switch variable { | |
Rápido | if condition {instructions} | if condition {instructions} | switch variable { | |
Perl | if (condition) {instructions} o unless (notcondition) {instructions} | if (condition) {instructions} o unless (notcondition) {instructions} | use feature "switch"; | condition ? valueIfTrue : valueIfFalse |
Raku | if condition {instructions} o unless notcondition {instructions} | if condition {instructions} | given variable { | condition ?? valueIfTrue !! valueIfFalse |
Rubí | if condition | if condition | case variable | condition ? valueIfTrue : valueIfFalse |
Escala | if (condition) {instructions} | if (condition) {instructions} | expression match { [b] | if (condition) valueIfTrue else valueIfFalse |
Charla informal | condition ifTrue: | condition ifTrue: trueBlock ifFalse: falseBlock | ||
Ceceo común | (when condition o o (unless condition (if condition | (cond (condition1 instructions) | (case expression | (if test then else) o (cond (test1 value1) (test2 value2) ...)) |
Esquema | (when condition instructions) o (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 | (cond (condition1 instructions) | (case expression | (if condition valueIfTrue valueIfFalse) |
Pascal | if condition then begin [do] | if condition then begin [do] | case variable of [do] | |
Visual Basic | If condition Then De una sola línea, cuando instructions son :instruction1 : instruction2 : ... If condition Then instructions «Else instructions» | If condition Then De una sola línea: consulte la nota sobre lenguajes similares a C; la Else cláusula de una declaración de una sola línea If puede contener otra declaración de una sola línea If . | Select« Case» variable | IIf(condition, valueIfTrue, valueIfFalse) |
Visual Basic .NET | If(condition, valueIfTrue, valueIfFalse) | |||
Xojo | ||||
Pitón [a] | if condition : | if condition : | Python 3.10+:match variable: | Python 2.5+:valueIfTrue if condition else valueIfFalse |
Jerga | if (condition) { instructions } «else { instructions }» | if (condition) { instructions } else if (condition) { instructions } ... «else { instructions }» | switch (variable) { case case1: instructions } { case case2: instructions } ... | |
Fortran | IF (condition) THEN | IF (condition) THEN | SELECT CASE(variable) | |
Adelante | condition IF instructions « ELSE instructions» THEN | condition IF instructions ELSE condition IF instructions THEN THEN | value CASE | 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 [b] | if condition then valueIfTrue else valueIfFalse |
F# | Modo de sintaxis ligera: Ya sea en una sola línea o con sangría como se muestra a continuación: Modo de sintaxis detallada: Igual que ML estándar. | Modo de sintaxis ligera: en una sola línea o con sangría como se muestra a continuación: Modo de sintaxis detallada: igual que ML estándar. if condition then | ||
ML estándar | if condition then «(»instructions «)» | if condition then «(»instructions «)» | case value of [b] | |
Haskell ( GHC ) | if condition then expression else expression o o when condition (do instructions) unless notcondition (do instructions) | result | condition = expression | case value of { [b] | |
Concha bash | if condition-command; then | if condition-command; then | case "$variable" in | |
Script de café | if condition then expression «else expression» o o o o if condition expression if condition unless condition expression unless condition | if condition then expression else if condition then expression «else expression» o o if condition unless condition | switch expression o switch expression | Todas las condiciones son expresiones. |
COBOL | IF condition «THEN» [d] | EVALUATE expression «ALSO expression...» | ||
Óxido | if condition { | if condition { | match variable { [ ser] | Todas las condiciones son expresiones |
si | De lo contrario si | seleccionar caso | expresión condicional |
END-IF
en lugar del punto al final.,
) al final de un brazo de coincidencia se puede omitir después del último brazo de coincidencia, o después de cualquier brazo de coincidencia en el que la expresión sea un bloque (termina en corchetes de coincidencia posiblemente vacíos{}
).bucle while | hacer bucle while | (bucle for controlado por conteo) | para cada uno | |
---|---|---|---|---|
Ada [1] | while condition loop | loop | for index in «reverse» [first .. last | discrete_type] loop | for item of «reverse» iterator loop o [b] (for [all | some] [in | of] [first .. last | discrete_type | iterator] => predicate) |
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» | «while statements; condition» | «for index» «from first» «by increment» «to last» do statements od | ||
APL | :While condition | :Repeat | :For var«s» :In list | :For var«s» :InEach list |
C ( C99 ) | instructions Puede ser una sola declaración o un bloque en forma de:{ statements } while (condition) instructions | do instructions while (condition); | for («type» i = first; i <= last; i++) instructions | — |
Objetivo-C | for (type item in set) instructions | |||
C++ (STL) | «std::»for_each(start, end, function) Desde C++11 : for (type item : set) instructions | |||
DO# | foreach (type item in set) instructions | |||
Java | for (type item : set) instructions | |||
JavaScript | for (var i = first; i <= last; i++) instructions | Desde EcmaScript 2015: [11]
| ||
PHP | foreach (range(first, last) as $i) instructions o for ($i = first; $i <= last; $i++) instructions | foreach (set as item) instructions o foreach (set as key => item) instructions | ||
Windows PowerShell | for ($i = first; $i -le last; $i++) instructions | foreach (item in set) instructions | ||
D | foreach (i; first ... last) instructions | foreach («type» item; set) instructions | ||
Ir | for condition { instructions } | for i := first; i <= last; i++ { instructions } | for key, item := range set { instructions } | |
Rápido | while condition { instructions } | 2.x: 1.x:repeat { instructions } while condition do { instructions } while condition | for i = first ... last { instructions } o o for i = first ..< last+1 { instructions } for var i = first; i <= last; i++ { instructions } | for item in set { instructions } |
Perl | while (condition) { instructions } o until (notcondition) { instructions } | do { instructions } while (condition) o do { instructions } until (notcondition) | for«each» «$i» (first .. last) { instructions } o for ($i = first; $i <= last; $i++) { instructions } | for«each» «$item» (set) { instructions } |
Raku | while condition { instructions } o until notcondition { instructions } | repeat { instructions } while condition o repeat { instructions } until notcondition | for first..last -> $i { instructions } o loop ($i = first; $i <=last; $i++) { instructions } | for set« -> $item» { instructions } |
Rubí | while condition o until notcondition | begin o begin | for i in first..last o o for i in first...last+1 first.upto(last) { |i| instructions } | for item in set o set.each { |item| instructions } |
Concha bash | while condition ;do o until notcondition ;do | — | for ((i = first; i <= last; ++i)) ; do | for item in set ;do |
Escala | while (condition) { instructions } | do { instructions } while (condition) | for (i <- first to last «by 1») { instructions } o first to last «by 1» foreach (i => { instructions }) | for (item <- set) { instructions } o set foreach (item => { instructions }) |
Charla informal | conditionBlock whileTrue: | loopBlock doWhile: | first to: last do: | collection do: |
Ceceo común | (loop o (do () (notcondition) | (loop | (loop o o (dotimes (i N) (do ((i first (1+ i))) ((>=i last)) | (loop o o o o (loop (dolist (item list) (mapc function list) (map type function sequence) |
Esquema | (do () (notcondition) instructions) o (let loop () (if condition (begin instructions (loop)))) | (let loop () (instructions (if condition (loop)))) | (do ((i first (+ i 1))) ((>= i last)) instructions) o (let loop ((i first)) (if (< i last) (begin instructions (loop (+ i 1))))) | (for-each (lambda (item) instructions) list) |
ISLISP | (while condition instructions) | (tagbody loop instructions (if condition (go loop)) | (for ((i first (+ i 1))) ((>= i last)) instructions) | (mapc (lambda (item) instructions) list) |
Pascal | while condition do begin | repeat | for i := first «step 1» to last do begin [a] | for item in set do instructions |
Visual Basic | Do While condition o o (Visual Basic .NET utiliza en su lugar) Do Until notcondition While condition End While | Do o Do | i Debe declararse previamente.
| For Each item In set |
Visual Basic .NET | For i« As type» = first To last« Step 1» [a] | For Each item« As type» In set | ||
Xojo | While condition | Do Until notcondition o Do | ||
Pitón | while condition : | — | Python 3.x: Python 2.x:for i in range(first, last+1): for i in xrange(first, last+1): | for item in set: |
Jerga | while (condition) { instructions } «then optional-block» | do { instructions } while (condition) «then optional-block» | for (i = first; i <= last; i++) { instructions } «then optional-block» | foreach item(set) «using (what)» { instructions } «then optional-block» |
Fortran | DO WHILE (condition) | DO | DO I = first,last | — |
Adelante | BEGIN «instructions» condition WHILE instructions REPEAT | BEGIN instructions condition UNTIL | limit start DO instructions LOOP | — |
OCaml | while condition do instructions done | — | for i = first to last do instructions done | Array.iter (fun item -> instructions) array o List.iter (fun item -> instructions) list |
F# | while condition do | — | for i = first to last do | foritem in set do o Seq.iter (fun item -> instructions) set |
ML estándar | while condition do ( instructions ) | — | Array.app (fn item => instructions) array o app (fn item => instructions) list | |
Haskell ( GHC ) | — | Control.Monad.forM_ [first..last] (\i -> do instructions) | Control.Monad.forM_list (\item -> do instructions) | |
Torre Eiffel | from | |||
Script de café | while condition o o o o o expression while condition while condition then expression until condition expression until condition until expression then condition | — | for i in [first..last] o o for i in [first..last] then expression expression for i in [first..last] | for item in set o o for item in set then expression expression for item in set |
COBOL | PERFORM procedure-1 «THROUGH procedure-2» ««WITH» TEST BEFORE» UNTIL condition [c]o PERFORM ««WITH» TEST BEFORE» UNTIL condition | PERFORM procedure-1 «THROUGH procedure-2» «WITH» TEST AFTER UNTIL condition [c]o PERFORM «WITH» TEST AFTER UNTIL condition | PERFORM procedure-1 «THROUGH procedure-2» VARYING i FROM first BY increment UNTIL i > last [d]o [d] PERFORM VARYING i FROM first BY increment UNTIL i > last | — |
Óxido | while condition { | loop { | for i in first..last+1 { o for i in first..=last { | for item in set { [e]o [e] set.into_iter().for_each(|item| expression); |
step
n" se utiliza para cambiar el intervalo del bucle. Sistep
se omite " ", el intervalo del bucle es 1.THRU
Se puede utilizar ^cTHROUGH
en lugar de .«IS» GREATER «THAN»
Se puede utilizar ^d>
en lugar de .std::iter::IntoIterator
.tirar | entrenador de animales | afirmación | |
---|---|---|---|
Ada [1] | raise exception_name «with string_expression» | begin [b] | pragma Assert («Check =>» boolean_expression ««Message =>» string_expression») |
APL | «string_expression» ⎕SIGNAL number_expression | :Trap number«s»_expression | «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 } ... | |
DO# | try { instructions } catch «(exception« name»)» { instructions } ... «finally { instructions }» | System.Diagnostics.Debug.Assert(condition); o System.Diagnostics.Trace.Assert(condition); | |
Java | try { instructions } catch (exception) { instructions } ... «finally { instructions }» | assert condition «: description»; | |
JavaScript | try { instructions } catch (exception) { instructions} «finally { instructions }» | ? | |
D | try { instructions } catch (exception) { instructions } ... «finally { instructions }» | assert(condition); | |
PHP | try { instructions } catch (exception) { instructions } ... «finally { instructions }» | assert(condition); | |
Jerga | try { instructions } catch «exception» { instructions } ... «finally { instructions }» | ? | |
Windows PowerShell | trap «[exception]» { instructions } ... instructions o try { instructions } catch «[exception]» { instructions } ... «finally { instructions }» | [Debug]::Assert(condition) | |
Objetivo-C | @throw exception; | @try { instructions } @catch (exception) { instructions } ... «@finally { instructions }» | NSAssert(condition, description); |
Rápido | 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 } ...}} | ? | |
Rubí | raise exception | begin | |
Charla informal | exception raise | instructionBlock on: exception do: handlerBlock | assert: conditionBlock |
Ceceo común | (error "exception") o o (error (error (make-condition | (handler-case o [a] (handler-bind | (assert condition) o o (assert condition (check-type var type) |
Esquema ( R 6 RS ) | (raise exception) | (guard (con (condition instructions) ...) instructions) | ? |
ISLISP | (error "error-string" objects) o (signal-condition condition continuable) | (with-handler | ? |
Pascal | raise Exception.Create() | try Except on E: exception do begin instructions end; end; | ? |
Visual Basic | Err.Raise ERRORNUMBER | With New Try: On Error Resume Next '*** Probar clase *** Descripción privada mstr como cadena Número privado mlng como largo Sub pública Catch () mstrDescription = Err . Descripción mlngNumber = Err . Número Fin Sub Propiedad pública Obtener número () Como número largo = mlngNumber Fin de propiedad Propiedad pública Obtener descripción () como cadena Descripción = mstrDescription Fin de la propiedad | Debug.Assert condition |
Visual Basic .NET | Throw exception o Error errorcode | Try | System.Diagnostics. Debug.Assert(condition) o System.Diagnostics.Trace.Assert(condition) |
Xojo | Raise exception | Try | — |
Pitón | raise exception | try: | assert condition |
Fortran | — | ||
Adelante | code THROW | xt CATCH ( code or 0 ) | — |
OCaml | raise exception | try expression with pattern -> expression ... | assert condition |
F# | try expression with pattern -> expression ... o try expression finally expression | ||
ML estándar | raise exception «arg» | expression handle pattern => expression ... | |
Haskell ( GHC ) | throw exception o throwError expression | catch tryExpression catchExpression o catchError tryExpression catchExpression | assert condition expression |
COBOL | RAISE «EXCEPTION» exception | USE «AFTER» EXCEPTION OBJECT class-name. o o o USE «AFTER» EO class-name. USE «AFTER» EXCEPTION CONDITION exception-name «FILE file-name». USE «AFTER» EC exception-name «FILE file-name». | — |
Óxido | No [13] | assert!(condition) |
with-simple-restart
ydefinir reinicios para su uso conrestart-case
.Las condiciones no controladas pueden hacer que la implementación muestre un menú de reinicios al usuario antes de desenrollar la pila.restart-bind
invoke-restart
bloque de salida (salto) | continuar | etiqueta | rama ( ir a) | valor de retorno del generador | |
---|---|---|---|---|---|
Ada [1] | exit «loop_name» «when condition» | — | label: | goto label | — |
ALGOL 68 | value exit; ... | do statements; skip exit; label: statements od | label: ... | go to label; ... | yield(value) ( Devolución de llamada ) [14] |
APL | :Leave | :Continue | label: | →label o :GoTo label | — |
C ( C99 ) | break; | continue; | label: | goto label; | — |
Objetivo-C | |||||
C++ (STL) | |||||
D | |||||
DO# | yield return value; | ||||
Java | break «label»; | continue «label»; | — | ||
JavaScript | yield value«;» | ||||
PHP | break «levels»; | continue «levels»; | goto label; | yield «key =>» value; | |
Perl | last «label»; | next «label»; | |||
Raku | |||||
Ir | break «label» | continue «label» | goto label | ||
Rápido | break «label» | continue «label» | — | ||
Concha bash | break «levels» | continue «levels» | — | — | — |
Ceceo común | (return) o o (return-from block) (loop-finish) | (tagbody tag | (go tag) | ||
Esquema | |||||
ISLISP | (return-from block) | (tagbody tag | (go tag) | ||
Pascal (ISO) | — | label: [a] | goto label; | — | |
Pascal ( FPC ) | break; | continue; | |||
Visual Basic | Exit block Alternativamente, para los métodos,Return | — | label: | GoTo label | |
Xojo | Continue block | ||||
Visual Basic .NET | Yield value | ||||
Pitón | break | continue | — | yield value | |
Juego de rol IV | LEAVE; | ITER; | |||
Jerga | break; | continue; | |||
Fortran | EXIT | CYCLE | label [b] | GOTO label | — |
Rubí | break | next | |||
Windows PowerShell | break «label» | continue | |||
OCaml | — | ||||
F# | |||||
ML estándar | |||||
Haskell ( GHC ) | |||||
COBOL | EXIT PERFORM o EXIT PARAGRAPH o EXIT SECTION oEXIT. | EXIT PERFORM CYCLE | label «SECTION». | GO TO label | — |
Consulte programación reflexiva para llamar y declarar funciones mediante cadenas.
llamando a una función | Función básica/nula | función que devuelve valor | función principal requerida | |
---|---|---|---|---|
Ada [1] | foo «(parameters)» | procedure foo «(parameters)» is begin statements end foo | function foo «(parameters)» return type is begin statements end foo | — |
ALGOL 68 | foo «(parameters)»; | proc foo = «(parameters)» void: ( instructions ); | proc foo = «(parameters)» rettype: ( instructions ...; retvalue ); | — |
APL | «parameters» foo parameters | foo←{ statements } | foo←{ statements } | — |
C ( C99 ) | foo(«parameters») | void foo(«parameters») { instructions } | type foo(«parameters») { instructions ... return value; } | «global declarations» |
Objetivo-C | ||||
C++ (STL) | ||||
Java | public static void main(String[] args) { instructions } o public static void main(String... args) { instructions } | |||
D | int main(«char[][] args») { instructions} o o o int main(«string[] args») { instructions} void main(«char[][] args») { instructions} void main(«string[] args») { instructions} | |||
DO# | Igual que el anterior; alternativamente, si solo hay una declaración:
| Igual que el anterior; alternativamente, si es lo suficientemente simple como para ser una expresión:
| static void Main(«string[] args») method_body En cambio, puede devolver int . (a partir de C# 7.1:) Puede devolver Task o Task<int> , y si es así, puede ser async . | |
JavaScript | function foo(«parameters») { instructions } o o var foo = function («parameters») { instructions } var foo = new Function ("«parameter»", ..., "«last parameter»" "instructions"); | function foo(«parameters») { instructions ... return value; } | — | |
Ir | func foo(«parameters») { instructions } | func foo(«parameters») type { instructions ... return value } | func main() { instructions } | |
Rápido | func foo(«parameters») { instructions } | func foo(«parameters») -> type { instructions ... return value } | — | |
Ceceo común | (foo «parameters») | (defun foo («parameters») o (setf (symbol-function 'symbol) | (defun foo («parameters») | — |
Esquema | (define (foo parameters) instructions) o (define foo (lambda (parameters) instructions)) | (define (foo parameters) instructions... return_value) o (define foo (lambda (parameters) instructions... return_value)) | ||
ISLISP | (defun foo («parameters») | (defun foo («parameters») | ||
Pascal | foo«(parameters)» | procedure foo«(parameters)»; «forward;»[a] | function foo«(parameters)»: type; «forward;»[a] | program name; |
Visual Basic | Foo(«parameters») | Sub Foo«(parameters)» | Function Foo«(parameters)»« As type» | Sub Main() |
Visual Basic .NET | Igual que el anterior; alternativamente:
| Sub Main(««ByVal »args() As String») oFunction Main(««ByVal »args() As String») As Integer | ||
Xojo | ||||
Pitón | foo(«parameters») | def foo(«parameters»): | def foo(«parameters»): | — |
Jerga | foo(«parameters» «;qualifiers») | define foo («parameters») { instructions } | define foo («parameters») { instructions ... return value; } | public define slsh_main () { instructions } |
Fortran | foo («arguments») [do] | SUBROUTINE sub_foo («arguments») [do] | type FUNCTION foo («arguments») [do] | PROGRAM main |
Adelante | «parameters» FOO | : FOO « stack effect comment: ( before -- ) » | : FOO « stack effect comment: ( before -- after ) » | — |
PHP | foo(«parameters») | function foo(«parameters») { instructions } | function foo(«parameters») { instructions ... return value; } | — |
Perl | foo(«parameters») o &foo«(parameters)» | sub foo { «my (parameters) = @_;» instructions } | sub foo { «my (parameters) = @_;» instructions... «return» value; } | |
Raku | foo(«parameters») o &foo«(parameters)» | «multi »sub foo(parameters) { instructions } | «our «type» »«multi »sub foo(parameters) { instructions ... «return» value; } | |
Rubí | foo«(parameters)» | def foo«(parameters)» | def foo«(parameters)» | |
Óxido | foo(«parameters») | fn foo(«parameters») { instructions } | fn foo(«parameters») -> type { instructions } | fn main() { instructions } |
Escala | 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 }; o function foo { «param(parameters)» instructions } | function foo «(parameters)» { instructions ... return value }; o function foo { «param(parameters)» instructions ... return value } | — |
Concha bash | foo «parameters» | function foo { o foo () { | function foo { o foo () { | |
| ||||
OCaml | foo parameters | let «rec» foo parameters = instructions | let «rec» foo parameters = instructions... return_value | |
F# | [<EntryPoint>] let main args = instructions | |||
ML estándar | fun foo parameters = ( instructions ) | fun foo parameters = ( instructions... return_value ) | ||
Haskell | foo parameters = do | foo parameters = return_value o foo parameters = do | «main :: IO ()» | |
Torre Eiffel | foo («parameters») | foo («parameters») | foo («parameters»): type | [b] |
Script de café | foo() | foo = -> | foo = -> value | — |
foo parameters | foo = () -> | foo = ( parameters ) -> value | ||
COBOL | CALL "foo" «USING parameters» [d] | «IDENTIFICATION DIVISION.» | «IDENTIFICATION DIVISION.» | — |
«FUNCTION» foo«(«parameters»)» | — |
forward;
" para declaraciones futuras .PARAMETER
es una palabra clave del lenguaje); laCALL
palabra clave es necesaria para las subrutinas."foo"
, se puede utilizar una variable de cadena que contenga el mismo valor.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)); or getf(proxy, ($dddd$, ivar)); | getf(proxy, ($g$, livar)); or getf(proxy, ($8d$, livar)); | getf(proxy, ($g$, rvar)); or getf(proxy, ($8d.4dE2d$, rvar)); | putf(proxy, ($g$, ival)); or putf(proxy, ($4d$, ival)); | putf(proxy, ($g(width, places, exp)$, rval)); or putf(proxy, ($8d.4dE2d$, rval)); | |
APL | ⍎string_expression | ⍎string_expression | ⍎string_expression | ⍕integer_expression | ⍕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 | string = [NSString stringWithFormat |
C++ (STL) | «std::»istringstream(string) >> number; | «std::»ostringstream o; o << number; string = o.str(); | |||
C++11 | integer = «std::»stoi(string); | long = «std::»stol(string); | float = «std::»stof(string); double = «std::»stod(string); | string = «std::»to_string(number); | |
C# | integer = int.Parse | long = long.Parse | float = float.Parse double = double.Parse | string = number | |
D | integer = std.conv.to!int | long = std.conv.to!long | float = std.conv.to!float double = std.conv.to!double | string = std.conv.to!string | |
Java | integer = Integer.parseInt | long = Long.parseLong | float = Float.parseFloat double = Double.parseDouble | string = Integer.toString string = String.valueOf | string = Float.toString string = Double.toString |
JavaScript[a] | integer = parseInt(string); | float = parseFloat(string); float = new Number (string); float = Number (string); float = +string; | string = number.toString (); string = String (number); string = number+""; string = `${number}` | ||
Go | integer, error = strconv.Atoi(string) | long, error = strconv.ParseInt | float, error = strconv.ParseFloat | string = strconv.Itoa(integer) string = strconv.FormatInt string = fmt.Sprint(integer) | string = strconv.FormatFloat string = fmt.Sprint |
Rust[d] | string.parse::<i32>() i32::from_str(string) | string.parse::<i64>() i64::from_str(string) | string.parse::<f64>() f64::from_str(string) | integer.to_string() | float.to_string() |
Common Lisp | (setf integer (parse-integer string)) | (setf float (read-from-string string)) | (setf string (princ-to-string number)) | ||
Scheme | (define number (string->number string)) | (define string (number->string number)) | |||
ISLISP | (setf integer (convert string <integer>)) | (setf float (convert string <float>)) | (setf string (convert number <string>)) | ||
Pascal | integer := StrToInt(string); | float := StrToFloat(string); | string := IntToStr(integer); | string := FloatToStr(float); | |
Visual Basic | integer = CInt(string) | long = CLng(string) | float = CSng(string) | string = CStr(number) | |
Visual Basic .NET (can use both VB syntax above and .NET methods shown right) | integer = Integer.Parse | long = Long.Parse | float = Single.Parse double = Double.Parse | string = number | |
Xojo | integer = Val(string) | long = Val(string) | double = Val(string) double = CDbl(string) | string = CStr(number) or string = Str(number) | |
Python | integer = int(string) | long = long(string) | float = float(string) | string = str(number) | |
S-Lang | integer = atoi(string); | long = atol(string); | float = atof(string); | string = string(number); | |
Fortran | READ(string,format) number | WRITE(string,format) number | |||
PHP | integer = intval(string); or integer = (int)string; | float = floatval(string); float = (float)string; | string = "$number"; or string = strval(number); or string = (string)number; | ||
Perl[b] | number = 0 + string; | string = "number"; | |||
Raku | number = +string; | string = ~number; | |||
Ruby | integer = string.to_i or integer = Integer(string) | float = string.to_f float = Float(string) | string = number.to_s | ||
Scala | integer = string.toInt | long = string.toLong | float = string.toFloat double = string.toDouble | string = number.toString | |
Smalltalk | integer := Integer readFrom: string | float := Float readFrom: string | string := number asString | ||
Windows PowerShell | integer = [int]string | long = [long]string | float = [float]string | string = [string]number; or string = "number"; or string = (number).ToString() | |
OCaml | let integer = int_ | let float = float_ | let string = string_ | let string = string_ | |
F# | let integer = int string | let integer = int64 string | let float = float string | let string = string number | |
Standard ML | val integer = Int | val float = Real | val string = Int | val string = Real | |
Haskell (GHC) | number = read string | string = show number | |||
COBOL | MOVE «FUNCTION» NUMVAL(string)[c] TO number | MOVE number TO numeric-edited |
NUMVAL-C
or NUMVAL-F
may be used instead of NUMVAL
.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.read from | write to | ||
---|---|---|---|
stdin | stdout | stderr | |
Ada[1] | Get (x) | Put (x) | Put (Standard_Error, x) |
ALGOL 68 | readf(($format$, x)); or getf(stand in, ($format$, x)); | printf(($format$, x)); or putf(stand out, ($format$, x)); | putf(stand error, ($format$, x)); [a] |
APL | x←⎕ | ⎕←x | ⍞←x |
C (C99) | scanf(format, &x); or fscanf(stdin, format, &x); [b] | printf(format, x); or fprintf(stdout, format, x); [c] | fprintf(stderr, format, x); [d] |
Objective-C | data = [[NSFileHandle fileHandleWithStandardInput] readDataToEndOfFile]; | [[NSFileHandle fileHandleWithStandardOutput] writeData:data]; | [[NSFileHandle fileHandleWithStandardError] writeData:data]; |
C++ | «std::»cin >> x; or «std::»getline(«std::»cin, str); | «std::»cout << x; | «std::»cerr << x; or «std::»clog << x; |
C# | x = Console.Read(); or x = Console.ReadLine(); | Console.Write(«format, »x); or Console.WriteLine(«format, »x); | Console.Error or Console.Error |
D | x = std.stdio.readln() | std.stdio.write(x) or std.stdio.writeln(x) or std.stdio.writef(format, x) or std.stdio.writefln(format, x) | stderr.write(x) or stderr.writeln(x) or std.stdio or std.stdio |
Java | x = System.in.read(); or x = new Scanner(System.in).nextInt(); or x = new Scanner(System.in).nextLine(); | System.out.print(x); or System.out.printf(format, x); or System.out.println(x); | System.err.print(x); or System.err.printf(format, x); or System.err.println(x); |
Go | fmt.Scan(&x) or fmt.Scanf(format, &x) or x = bufio.NewReader(os.Stdin).ReadString('\n') | fmt.Println(x) or fmt.Printf(format, x) | fmt.Fprintln(os.Stderr, x) or fmt.Fprintf(os.Stderr, format, x) |
Swift | x = readLine() (2.x) | print(x) (2.x)println(x) (1.x) | |
JavaScript Web Browser implementation | document.write(x) | ||
JavaScript Active Server Pages | Response.Write(x) | ||
JavaScript Windows Script Host | x = WScript.StdIn.Read(chars) or x = WScript.StdIn.ReadLine() | WScript.Echo(x) or WScript.StdOut.Write(x) or WScript.StdOut.WriteLine(x) | WScript.StdErr.Write(x) or WScript.StdErr.WriteLine(x) |
Common Lisp | (setf x (read-line)) | (princ x) or (format t format x) | (princ x *error-output*) or
|
Scheme (R6RS) | (define x (read-line)) | (display x) or
| (display x (current-error-port)) or
|
ISLISP | (setf x (read-line)) |
|
|
Pascal | read(x); or readln(x); | write(x); or writeln(x); | write(stderr, x); or writeln(stderr, x); |
Visual Basic | Input« prompt,» x | Print x or ? x | — |
Visual Basic .NET | x = Console.Read() or x = Console.ReadLine() | Console.Write(«format,»x) or Console.WriteLine(«format, »x) | Console.Error or Console.Error |
Xojo | x = StandardInputStream.Read() or x = StandardInputStreame.ReadLine() | StandardOutputStream.Write(x) or StandardOutputStream.WriteLine(x) | StdErr.Write(x) or StdErr.WriteLine(x) |
Python 2.x | x = raw_input(«prompt») | print x or sys.stdout.write(x) |
or sys.stderr.write(x) |
Python 3.x | x = input(«prompt») | print(x«, end=""») | print(x«, end=""», file=sys.stderr) |
S-Lang | fgets (&x, stdin) | fputs (x, stdout) | fputs (x, stderr) |
Fortran | READ(*,format) variable names or READ(INPUT_UNIT,format) variable names [e] | WRITE(*,format) expressions or WRITE(OUTPUT_UNIT,format) expressions [e] | WRITE(ERROR_UNIT,format) expressions [e] |
Forth | buffer length ACCEPT ( # chars read ) | buffer length TYPE | — |
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; |
Raku | $x = $*IN.get; | x.print or x.say | x.note or $*ERR.print(x) or $*ERR.say(x) |
Ruby | x = gets | puts x or printf(format, x) | $stderr.puts(x) or $stderr.printf(format, x) |
Windows PowerShell | $x = Read-Host«« -Prompt» text»; or $x = [Console]::Read(); or $x = [Console]::ReadLine() | x; or Write-Output x; or echo x | Write-Error x |
OCaml | let x = read_int () or let str = read_line () or Scanf.scanf format (fun x ... -> ...) | print_int x or print_endline str or Printf.printf format x ... | prerr_int x or prerr_endline str or Printf.eprintf format x ... |
F# | let x = System.Console.ReadLine() | printf format x ... or printfn format x ... | eprintf format x ... or eprintfn format x ... |
Standard ML | val str = TextIO.inputLIne TextIO.stdIn | print str |
|
Haskell (GHC) | x <- readLn or str <- getLine | print x or putStrLn str | hPrint stderr x or hPutStrLn stderr str |
COBOL | ACCEPT x | DISPLAY x |
read
, write
, get
, and put
.gets(x)
and fgets(x, length, stdin)
read unformatted text from stdin. Use of gets is not recommended.puts(x)
and fputs(x, stdout)
write unformatted text to stdout.fputs(x, stderr)
writes unformatted text to stderrArgument values | Argument counts | Program name / Script name | |
---|---|---|---|
Ada[1] | Argument (n) | Argument_Count | Command_Name |
C (C99) | argv[n] | argc | first argument |
Objective-C | |||
C++ | |||
C# | args[n] | args.Length | Assembly.GetEntryAssembly() |
Java | args.length | ||
D | first argument | ||
JavaScript Windows Script Host implementation | WScript.Arguments(n) | WScript.Arguments.length | WScript.ScriptName or WScript.ScriptFullName |
Go | os.Args[n] | len(os.Args) | first argument |
Rust[a] | std::env::args().nth(n) std::env::args_os().nth(n) | std::env::args().count() std::env::args_os().count() | std::env::args().next() std::env::args_os().next() |
Swift | Process.arguments[n] orProcess.unsafeArgv[n] | Process.arguments.count orProcess.argc | first argument |
Common Lisp | ? | ? | ? |
Scheme (R6RS) | (list-ref (command-line) n) | (length (command-line)) | first argument |
ISLISP | — | — | — |
Pascal | ParamStr(n) | ParamCount | first argument |
Visual Basic | Command [b] | — | App.Path |
Visual Basic .NET | CmdArgs(n) | CmdArgs.Length | [Assembly].GetEntryAssembly().Location |
Xojo | System.CommandLine | (string parsing) | Application.ExecutableFile.Name |
Python | sys.argv[n] | len(sys.argv) | first argument |
S-Lang | __argv[n] | __argc | first argument |
Fortran | DO i = 1,argc | argc = COMMAND_ARGUMENT_COUNT () | CALL GET_COMMAND_ARGUMENT (0,progname) |
PHP | $argv[n] | $argc | first argument |
Bash shell | $n ($1, $2, $3, ...) $@ (all arguments) | $# | $0 |
Perl | $ARGV[n] | scalar(@ARGV) | $0 |
Raku | @*ARGS[n] | @*ARGS.elems | $PROGRAM_NAME |
Ruby | ARGV[n] | ARGV.size | $0 |
Windows PowerShell | $args[n] | $args.Length | $MyInvocation.MyCommand |
OCaml | Sys.argv.(n) | Array.length Sys.argv | first argument |
F# | args.[n] | args.Length | Assembly.GetEntryAssembly() |
Standard ML | List.nth (CommandLine.arguments (), n) | length (CommandLine.arguments ()) | CommandLine.name () |
Haskell (GHC) | do { args <- System.getArgs; return length args !! n } | do { args <- System.getArgs; return length args } | System.getProgName |
COBOL | [c] | — |
std::env::args
and std::env::args_os
return iterators, std::env::Args
and std::env::ArgsOs
respectively. Args
converts each argument to a String
and it panics if it reaches an argument that cannot be converted to UTF-8. ArgsOs
returns a non-lossy representation of the raw strings from the operating system (std::ffi::OsString
), which can be invalid UTF-8.Split(string)
.ACCEPT
statements.Shell command | Execute program | Replace current program with new executed program | |
---|---|---|---|
Ada[1] | Not part of the language standard. Commonly done by compiler provided packages or by interfacing to C or POSIX.[16] | ||
C | system("command"); | execl(path, args); or execv(path, arglist); | |
C++ | |||
Objective-C | [NSTask launchedTaskWithLaunchPath:(NSString *)path arguments:(NSArray *)arguments]; | ||
C# | System.Diagnostics | ||
F# | |||
Go | exec.Run(path, argv, envv, dir, exec.DevNull, exec.DevNull, exec.DevNull) | os.Exec(path, argv, envv) | |
Visual Basic | Interaction.Shell(command «, WindowStyle» «, isWaitOnReturn») | ||
Visual Basic .NET | Microsoft.VisualBasic | System.Diagnostics | |
Xojo | Shell.Execute(command «, Parameters») | FolderItem.Launch(parameters, activate) | — |
D | std.process.system("command"); | std.process.execv(path, arglist); | |
Java | Runtime.exec(command); or new ProcessBuilder(command).start(); | ||
JavaScript Windows Script Host implementation |
| WshShell.Exec(command) | |
Common Lisp | (uiop:run-program command) | ||
Scheme | (system command) | ||
ISLISP | — | — | — |
Pascal | system(command); | ||
OCaml | Sys.command command, Unix.open_process_full command env (stdout, stdin, stderr),... | Unix.create_process prog args new_stdin new_stdout new_stderr, ... | Unix.execv prog args or Unix.execve prog args env |
Standard ML | OS.Process.system command | Unix.execute (path, args) | Posix.Process.exec (path, args) |
Haskell (GHC) | System.system command | System.Process | Posix.Process |
Perl | system(command) or $output = `command` or $output = qx(command) | exec(path, args) | |
Ruby | system(command) or output = `command` | exec(path, args) | |
PHP | system(command) or $output = `command` or exec(command) or passthru(command) | ||
Python | os.system(command) or subprocess.Popen(command) | subprocess.call(["program", "arg1", "arg2", ...]) | os.execv(path, args) |
S-Lang | system(command) | ||
Fortran | CALL EXECUTE_COMMAND_LINE (COMMAND «, WAIT» «, EXITSTAT» «, CMDSTAT» «, CMDMSG») [a] | ||
Windows PowerShell | [Diagnostics.Process]::Start(command) | «Invoke-Item »program arg1 arg2 ... | |
Bash shell | output=`command` or output=$(command) | program arg1 arg2 ... |
^a Fortran 2008 or newer.[17]