Comparaison des langages de programmation (instructions de base) - Comparison of programming languages (basic instructions)

Cet article compare un grand nombre de langages de programmation en tablant leurs types de données , leur expression , instruction et syntaxe de déclaration , ainsi que certaines interfaces de système d'exploitation courantes.

Conventions de cet article

Le gras est le code littéral. Le non gras est interprété par le lecteur. Les mentions en guillemets (« ... ») sont facultatives. Tab ↹indique un retrait nécessaire (avec espace).

Identificateurs de type

Entiers

8 bits ( octet ) 16 bits ( entier court ) 32 bits 64 bits ( entier long ) Taille de mot arbitrairement précis ( bignum )
Signé Non signé Signé Non signé Signé Non signé Signé Non signé Signé Non signé
Ada range -2**7 .. 2**7 - 1 range 0 .. 2**8 - 1 ou alors mod 2**8 range -2**15 .. 2**15 - 1 range 0 .. 2**16 - 1 ou alors mod 2**16 range -2**31 .. 2**31 - 1 range 0 .. 2**32 - 1 ou alors mod 2**32 range -2**63 .. 2**63 - 1 mod 2**64 Integer range 0 .. 2**Integer'Size - 1 ou alors mod Integer'Size N / A
ALGOL 68 (largeur variable) short short int N / A short int N / A int N / A long int N / A int N / A long long int
bytes & bits
C ( C99 à largeur fixe) int8_t uint8_t int16_t uint16_t int32_t uint32_t int64_t uint64_t intptr_t size_t N / A
C++ ( C++11 à largeur fixe)
C ( C99 à largeur variable) signed char unsigned char short unsigned short long unsigned long long long unsigned long long int unsigned int
C++ ( C++11 à largeur variable)
Objective-C ( Cacao ) 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)
Java byte N / A char N / A N / A N / A N / A java.math.BigInteger
Va int8 uint8 ou alors byte int16 uint16 int32 uint32 int64 uint64 int uint big.Int
Rouiller i8 u8 i16 u16 i32 u32 i64 u64 isize usize N / A
Rapide Int8 UInt8 Int16 UInt16 Int32 UInt32 Int64 UInt64 Int UInt
byte ubyte short ushort int uint long ulong N / A N / A BigInt
Lisp commun (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
Schème
ISLISP 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)
GratuitBasic Byte ou alors Integer<8> UByte ou alors UInteger<8> Short ou alors Integer<16> UShort ou alors UInteger<16> Long ou alors Integer<32> ULong ou alors UInteger<32> LongInt ou alors Integer<64> ULongInt ou alors UInteger<64> 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
Argot N / A N / A N / A N / A N / A N / A
Fortran INTEGER(KIND = n) N / A INTEGER(KIND = n) N / A INTEGER(KIND = n) N / A INTEGER(KIND = n) N / A
PHP N / A N / A int N / A int N / A N / A
Perl 5 N / A N / A N / A N / A N / A Math::BigInt
Raku int8 uint8 int16 uint16 int32 uint32 int64 uint64 Int N / A
Rubis N / A N / A N / A N / A Fixnum N / A Bignum
Erlang N / A N / A N / A N / A entier() N / A entier()
Scala Byte N / A Short Char Int N / A Long N / A N / A N / A scala.math.BigInt
Graine7 N / A N / A N / A N / A N / A N / A integer N / A N / A N / A bigInteger
Petite conversation N / A N / A N / A N / A SmallInteger N / A LargeInteger
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;;
big_int
F# sbyte byte int16 uint16 int32 ou alors int uint32 uint64 nativeint unativeint bigint
ML standard N / A Word8.word N / A Int32.int Word32.word Int64.int Word64.word int word LargeInt.int ou alors
IntInf.int
Haskell ( GHC ) « import Int»
Int8
« import Word»
Word8
« import Int»
Int16
« import Word»
Word16
« import Int»
Int32
« import Word»
Word32
« import Int»
Int64
« import Word»
Word64
Int « import Word»
Word
Integer
Eiffel INTEGER_8 NATURAL_8 INTEGER_16 NATURAL_16 INTEGER_32 NATURAL_32 INTEGER_64 NATURAL_64 INTEGER NATURAL N / A
COBOL 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
Mathématique N / A N / A N / A N / A N / A Integer
Langage Wolfram N / A N / A N / A N / A N / A Integer

^a Lesconstantesstandardint shortsetint lengthspeuvent être utilisées pour déterminer combien de 'short' et 'long' peuvent être utilement préfixés à 'short int' et 'long int'. La taille de la réalité «short int», «int» et «long int» est disponibletant que constantesshort max int,max intetlong max intetc.
^ b couramment utilisés pourcaractères.
^c Les langages ALGOL 68, C et C++ ne spécifient pas la largeur exacte des types entiersshort,int,long, et (C99, C++11)long long, ils dépendent donc de l'implémentation. En C et C++short, lestypeslongetlong longdoivent avoir une largeur d'au moins 16, 32 et 64 bits, respectivement, mais peuvent être plus. Leinttype doit être au moins aussi large queshortet au plus aussi large quelong, et correspond généralement à la largeur de la taille du mot sur le processeur de la machine (c'est-à-dire sur une machine 32 bits, elle est souvent de 32 bits ; sur 64 -bit machines, il fait parfois 64 bits de large). C99 et C++11 définissent également les[u]intN_ttypes de largeur exacte dans l'en-têtestdint.h. VoirC syntax#Integral typespour plus d'informations. De plus, les typessize_tetptrdiff_tsont définis par rapport à la taille de l'adresse pour contenir des entiers non signés et signés suffisamment grands pour gérer les indices de tableau et la différence entre les pointeurs.
^d Perl 5 n'a pas de types distincts. Les entiers, les nombres à virgule flottante, les chaînes, etc. sont tous considérés comme des "scalaires".
^e PHP a deux bibliothèques de précision arbitraire. La bibliothèque BCMath utilise uniquement des chaînes comme type de données. La bibliothèque GMP utilise un type "ressource" interne.
^f La valeur de "n" est fournie par laSELECTED_INT_KINDfonction intrinsèque.
^g L'option d'exécution de l'ALGOL 68G--precision "number"peut définir la précision delong long ints sur le "nombre" de chiffres significatifs requis. Lesconstantesstandardlong long int widthetlong long max intpeuvent être utilisées pour déterminer la précision réelle.
^h COBOLpermet de spécifier une précision requise et sélectionnera automatiquement un type disponible capable de représenter la précision spécifiée. "PIC S9999", par exemple, nécessiterait une variable signée d'une précision de quatre chiffres décimaux. S'il est spécifié en tant que champ binaire, cela sélectionnera un type signé 16 bits sur la plupart des plates-formes.
^i Smalltalkchoisit automatiquement une représentation appropriée pour les nombres entiers. En règle générale, deux représentations sont présentes, une pour les entiers correspondant à la taille du mot natif moins tout bit de balise (SmallInteger) et l'autre prenant en charge les entiers de taille arbitraire (LargeInteger). Les opérations arithmétiques prennent en charge les arguments polymorphes et renvoient le résultat dans la représentation compacte la plus appropriée.
^j Les types de plageAdasont vérifiés pour les violations de limites au moment de l'exécution (ainsi qu'au moment de la compilation pour les expressions statiques). Les violations des limites d'exécution déclenchent une exception « erreur de contrainte ». Les portées ne sont pas limitées aux puissances de deux. Les sous-types d'entiers généralement prédéfinis sont : Positif (range 1 .. Integer'Last) et Naturel (range 0 .. Integer'Last). Short_Short_Integer(8 bits),Short_Integer(16 bits) etLong_Integer(64 bits) sont également couramment prédéfinis, mais pas requis par la norme Ada. Les contrôles à l'exécution peuvent être désactivés si les performances sont plus importantes que les contrôles d'intégrité.
^k Les types moduloAdaimplémentent l'arithmétique modulo dans toutes les opérations, c'est-à-dire qu'aucune violation de plage n'est possible. Les modulos ne sont pas limités aux puissances de deux.
^l Couramment utilisé pour les caractères comme le char de Java.
^m int en PHP a la même largeur que lelongtype en C sur ce système.
^n Erlangest typé dynamiquement. Les identificateurs de type sont généralement utilisés pour spécifier les types de champs d'enregistrement et les types d'argument et de retour des fonctions.
^o Lorsqu'il dépasse un mot.

Point flottant

Simple précision Double precision Autre précision Dépend du processeur
Ada Float Long_Float N / A
ALGOL 68 real long real short real, long long real, etc
C float double long double
C++ (LIST)
Objective-C (Cacao) CGFloat
C# float N / A
Java
Va float32 float64
Rouiller f32 f64
Rapide Float
Float32
Double
Float64
Float80 CGFloat
float double real
Lisp commun single-float double-float float, short-float, long-float
Schème
ISLISP
Pascal (Pascal libre) single double real
Visual Basic Single Double N / A
Visual Basic .NET
Xojo
Python N / A float
JavaScript Number N / A
Argot
Fortran REAL(KIND = n)
PHP float
Perl
Raku num32 num64 Num
Rubis N / A Float N / A
Scala Float Double
Graine7 N / A float
Petite conversation Float Double
Windows PowerShell
OCaml N / A float N / A
F# float32
ML standard N / A real
Haskell (GHC) Float Double
Eiffel REAL_32 REAL_64
COBOL FLOAT-BINARY-7 FLOAT-BINARY-34 FLOAT-SHORT, FLOAT-LONG,FLOAT-EXTENDED
Mathématique N / A N / A Real

^a Lesconstantesstandardreal shortsetreal lengthspeuvent être utilisées pour déterminer combien de 'short' et 'long' peuvent être utilement préfixés à 'short real' et 'long real'. La taille de la réalité «short real», «real» et «long real» est disponibletant que constantesshort max real,max realetlong max realetc. Avec les constantesshort small real,small realetlong small realdisponibles pour chaque type demachine de epsilon.
^b les déclarations de simple précision ne sont souvent pas respectées
^c La valeur de "n" est fournie par laSELECTED_REAL_KINDfonction intrinsèque.
^d L'option d'exécution de l'ALGOL 68G--precision "number"peut définir la précision delong long reals sur le "nombre" de chiffres significatifs requis. Lesconstantesstandardlong long real widthet 'long long max realpeuvent être utilisées pour déterminer la précision réelle.
^e Ces types à virgule flottante IEEE seront introduits dans la prochaine norme COBOL.
^f Même taille que 'double' sur de nombreuses implémentations.
^g Swift prend en charge letype à virgule flottante àprécision étendue80 bits, équivalent auxlong doublelangages C.

Nombres complexes

Entier Simple précision Double precision Demi et quadruple précision etc.
Ada N / A Complex Complex Complex
ALGOL 68 N / A compl long compl etc. short completc. & long long completc.
C (C99) N / A float complex double complex N / A
C++ (LIST) N / A std::complex<float> std::complex<double>
C# N / A N / A System.Numerics.Complex
(.NET 4.0)
Java N / A N / A N / A
Va N / A complex64 complex128
N / A cfloat cdouble
Objectif c N / A N / A N / A
Lisp commun (entier complexe) (flotteur simple complexe) (double flotteur complexe) complexe
Schème 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
JavaScript N / A N / A
Argot N / A N / A
Fortran COMPLEX(KIND = n)
Rubis Complex N / A Complex
Scala N / A N / A N / A
Graine7 N / A N / A complex
Petite conversation Complex Complex Complex
Windows PowerShell N / A N / A
OCaml N / A N / A Complex.t
F# System.Numerics.Complex
(.NET 4.0)
ML standard 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
Mathématique Complex N / A N / A Complex

^a La valeur de "n" est fournie par laSELECTED_REAL_KINDfonction intrinsèque.

^b Type générique qui peut être instancié avec n'importe quel type de base à virgule flottante.

Autres types de variables

Texte booléen Énumération Objet / Universel
Personnage Chaîne
Ada Character String, Bounded_String,Unbounded_String Boolean ( item1, item2, ... ) tagged null record
ALGOL 68 char string, bytes bool, bits N/A - Défini par l'utilisateur N / A
C (C99) char, wchar_t N / A bool enum «name» { item1, item2, ... }; void *
C++ (LIST) «std::»string
Objectif c unichar NSString * BOOL id
C# char string bool enum name { item1« = value», item2« = value», ... } objet
Java String boolean enum name { item1, item2, ... } Object
Va byte, rune string bool
const (
  item1 = iota
  item2
  ...
)
interface{}
Rouiller char String bool
enum name { item1« = value», item2« = value», ... }
std::any::Any
Rapide Character String Bool enum name { case item1, item2, ... } Any
char string bool enum name { item1, item2, ... } std.variant.Variant
Lisp commun character string boolean (member item1 item2 ...) t
Schème
ISLISP
Pascal (ISO) char N / A boolean ( item1, item2, ... ) N / A
Pascal Objet (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 ou alors Variant
Python N / A str bool
from enum import Enum
class Name(Enum):
  item1 = value
  item2 = value
  ...
object
JavaScript N / A String Boolean Object
Argot
Fortran CHARACTER(LEN = *) CHARACTER(LEN = :), allocatable LOGICAL(KIND = n) CLASS(*)
PHP N / A string bool (déclaration de type omise)
Perl N / A UNIVERSAL
Raku Char Str Bool enum name<item1 item2 ...>
enum name <<:item1(value) :item2(value) ..>>
Mu
Rubis N / A String Object Object
Scala Char String Boolean
object name extends Enumeration {
  val item1, item2, ... = Value
}
Any
Graine7 char string boolean
const type: name is new enum
  item1,
  item2,
  ...
end enum;
Windows PowerShell
OCaml char string bool N / A N / A
F# type name = item1 = value |item2 = value | ... obj
ML standard N / A N / A
Haskell (GHC) Char String Bool N / A N / A
Eiffel CHARACTER STRING BOOLEAN N / A ANY
COBOL PIC X PIC X(string length) ou alors PIC X«X...» PIC 1«(number of digits ou alors PIC 1«1...» N / A OBJECT REFERENCE
Mathématique N / A String N / A

^a spécifiquement, des chaînes de longueur arbitraire et gérées automatiquement.
^b Ce langage représente un booléen sous forme d'entier où false est représenté par une valeur de zéro et true par une valeur non nulle.
^c Toutes les valeurs sont évaluées à vrai ou à faux. Tout dansTrueClassévalue à vrai et tout dansFalseClassévalue à faux.
^d Cette langue n'a pas de type de caractère distinct. Les caractères sont représentés sous forme de chaînes de longueur 1.
^e Les énumérations dans ce langage sont des types algébriques avec uniquement des constructeurs nuls
^f La valeur de "n" est fournie par laSELECTED_INT_KINDfonction intrinsèque.

Types dérivés

Déployer

tableau de taille fixe tableau de taille dynamique
tableau à une dimension tableau multidimensionnel tableau à une dimension tableau multidimensionnel
Ada array (<first> .. <last>) of <type>
ou alors
array (<discrete_type>) of <type>
array (<first1> .. <last1>, <first2> .. <last2>, ...) of <type>
or
array (<discrete_type1>, <discrete_type2>, ...) of <type>
array (<discrete_type> range <>) of <type> array (<discrete_type1> range <>, <discrete_type2> range <>, ...) of <type>
ALGOL 68 [first:last]«modename»
ou simplement:
[size]«modename»
[first1:last1, first2:last2]«modename»
ou etc
[first1:last1][first2:last2]«modename»
flex[first:last]«modename»
ou simplement:
flex[size]«modename»
flex[first1:last1, first2:last2]«modename»
ou alors
flex[first1:last1]flex[first2:last2]«modename» etc.
C (C99) type name[size] type name[size1][size2] type *name
ou dans un bloc :
int n = ...; type name[n]
C++ (LIST) «std::»array<type, size>(C++11) «std::»vector<type>
C# type[] type[,,...] System.Collections.ArrayList
or
System.Collections.Generic.List<type>
Java type[] type[][]... ArrayList or ArrayList<type>
type[size] type[size1][size2] type[]
Va [size]type [size1][size2]...type []type [][]type
Rouiller [type; size] [[type; size1]; size2] Vec<type> Vec<Vec<type>>
Rapide [type] ou alors Array<type> [[type]] ou alors Array<Array<type>>
Objectif c NSArray NSMutableArray
JavaScript N / A N / A Array
Lisp commun (simple-array type (dimension)) (simple-array type (dimension1 dimension2)) (array type (dimension)) (array type (dimension1 dimension2))
Schème
ISLISP
Pascal array[first..last] of type array[first1..last1] of array[first2..last2] ... of type

ou alors
array[first1..last1, first2..last2, ...] of type

N / A N / A
Pascal Objet (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.ArrayList
or
System.Collections.Generic.List(Of type)
Python list
Argot 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
Rubis x = Array.new(size1){ Array.new(size2) } Array
Scala Array[type] Array[...[Array[type]]...] ArrayBuffer[type]
Graine7 array type
or
array [idxType] type
array array type
or
array [idxType] array [idxType] type
array type
or
array [idxType] type
array array type
or
array [idxType] array [idxType] type
Petite conversation Array OrderedCollection
Windows PowerShell type[] type[,,...]
OCaml type array type array ... array
F# type [] or type array type [,,...] System.Collections.ArrayList
or
System.Collections.Generic.List<type>
ML standard 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. N / A

^a Dans la plupart des expressions (à l'exception desopérateurssizeofet&), les valeurs des types de tableau en C sont automatiquement converties en un pointeur de son premier argument. VoirC syntax#Arrayspour plus de détails sur la syntaxe et les opérations de pointeur.
^b Le C-likefonctionne en Java, maisc'est la forme préférée de déclaration de tableau. ^c Les sous- plages sont utilisées pour définir les limites du tableau. ^d Les tableaux de JavaScript sont un type particulier d'objet. ^e Laclause dans COBOL ne crée pas un "vrai" tableau de longueur variable et allouera toujours la taille maximale du tableau. type x[]type[] x


DEPENDING ON

Autres types

Types composites simples Types de données algébriques Syndicats
Enregistrements Expression de tuple
Ada
type name is «abstract» «tagged» «limited» [record
  field1 : type;
  field2 : type;
  ...
end record | null record]
N / A Toute combinaison d'enregistrements, d'unions et d'énumérations (ainsi que des références à ceux-ci, permettant des types récursifs).
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», ...); Les types et opérateurs requis peuvent être définis par l'utilisateur union (modename, ...);
C (C99) struct «name» {type name;...}; N / A N / A union {type name;...};
Objectif c
C++ struct «name» {type name;...}; «std::»tuple<type1..typen>
C# struct name {type name;...} (val1, val2, ... ) N / A
Java N / A
JavaScript N / A
struct name {type name;...} std.variant.Algebraic!(type,...) union {type name;...}
Va
struct {
  «name» type
  ...
}
Rouiller struct name {name: type, ...} (val1, val2, ... ) enum name { Foo(types), ...} union name {name: type, ...}
Rapide
struct name {
  var name «: type»
  ...
}
(«name1:» val1, «name2:» val2, «name3:» val3, ... ) enum name { case Foo«(types)» case Bar «(types)» ... }
Lisp commun (defstruct name slot-name (slot-name initial-value) (slot-name initial-value :type type) ...) (cons val1 val2)
Schème 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 «(»val1, val2, val3, ... «)» N / A
Argot struct {name [=value], ...}
Fortran
TYPE name
  type :: name
  ...
END TYPE
PHP N / A
Perl N / A N / A
Raku N / A
Rubis 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
  ...

ou alors

abstract class name
  case object Foo extends name
  case object Bar extends name
  ...

ou combinaison de classes de cas et d'objets de cas

Windows PowerShell
OCaml type name = {«mutable» name : type;...} «(»val1, val2, val3, ... «)» type name = Foo «of type» | Bar «of type» | ... N / A
F#
ML standard 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 Seules les classes sont prises en charge.
Les ^b struct en C++ sont en fait des classes, mais ont une visibilité publique par défaut etsontégalement desobjetsPOD. C++11 a étendu cela plus loin, pour que les classes agissent de manière identique aux objets POD dans de nombreux cas.
^c paire uniquement
^d Bien que Perl n'ait pas d'enregistrements, car le système de types de Perl permet à différents types de données d'être dans un tableau, les "hachages" (tableaux associatifs) qui n'ont pas d'index de variable seraient effectivement les mêmes que les enregistrements .
^e Les énumérations dans ce langage sont des types algébriques avec seulement des constructeurs nuls

Déclarations de variables et de constantes

variable constant type synonyme
Ada identifier : type« := initial_value» 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;
Objectif c
C++ const type name = value;
C# type name1« = initial_value», name2« = initial_value», ... ; or
var name = initial_value;
const type name = value, name = value, ... ; or
readonly type name = value, name = value, ... ;
using synonym = type;
type name« = initial_value»; or
auto name = value;
const type name = value; or
immutable type name = value;
alias type synonym;
Java type name« = initial_value»; final type name = value; N / A
JavaScript var name« = initial_value»;ou (depuis ECMAScript 2015)
let name« = initial_value»;
const name = value;(depuis ECMAScript 2015)
Va var name type« = initial_value» or
name := initial_value
const name «type» = value type synonym type
Rouiller 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;
Rapide var name« : type»« = initial_value» let name «: type» = value typealias synonym = type
Lisp commun (defparameter name initial-value) or
(defvar name initial-value)
(defconstant name value) (deftype synonym () 'type)
Schème (define name initial_value)
ISLISP (defglobal name initial_value) or
(defdynamic name initial_value)
(defconstant name value) N / A
Pascal name: type« = initial_value» name = value synonym = type
Visual Basic Dim name «As type» Voir les notes à gauche.

Les constantes utilisent la même syntaxe et :

  • utiliser Constau lieu deDim
  • avoir une restriction à certains types primitifs seulement

Const name1 «As type» = value, name2 «As type» = value, ...

Visual Basic .NET La syntaxe de déclaration de variable de VB.NET est étonnamment difficile à décrire avec précision.

Sachant qu'il existe des suffixes d'identifiants ("modificateurs") :

  • type_character, disponible comme alternative à une Asclause pour certains types de données primitifs ;
  • nullable_specifier; et
  • array_specifier;

et cela

  • a modified_identifierest de la forme identifier«type_character»«nullable_specifier»«array_specifier»;
  • a modified_identifier_listest une liste séparée par des virgules de deux occurrences ou plus de modified_identifier; et
  • a declarator_listest une liste de déclarateurs séparés par des virgules, qui peut être de la forme
    • identifier As object_creation_expression (déclarateur d'initialiseur d'objet) ,
    • modified_identifier« As non_array_type«array_rank_specifier»»« = initial_value» (déclarant unique) , ou
    • modified_identifier_list« As «non_array_type««array_rank_specifier»» (déclarateur multiple);

les déclarations de déclaration valides sont de la forme

Dim declarator_list,

où, à des fins d'analyse sémantique, pour convertir le declarator_listen une liste de déclarateurs uniques :

Les Asclauses de chaque déclarant multiple sont réparties sur sonmodified_identifier_list
Le As New type...de chaque déclarateur d'initialiseur d'objet est remplacé parAs type = New type...

et pour lequel, pour chaque identifier,

  • a type_characteret la Asclause n'apparaissent pas toutes les deux ;
  • si une Asclause est présente,
    • un array_rank_specifiern'apparaît pas à la fois comme une modification de l'identifiant et sur le type de la Asclause ;
  • an unmodified_typepeut être déterminé, par la règle selon laquelle,
    • si une clause type_characterou Asest présente,
      • unmodified_type est celui spécifié par une telle construction,
    • et que sinon,
      • soit Option Inferdoit être activé et identifierdoit avoir un initialiseur, auquel cas unmodified_typeest celui de l'initialiseur, ou
      • Option Strictdoit être éteint, auquel cas unmodified_typeest Object;
  • son final_typeest son unmodified_typepréfixé avant ses modificateurs;
  • son final_typeest un type valide; et
  • si un initial_valueest présent,
    • soit Option Strictest activé et initial_valuea une conversion qui s'élargit vers final_type, ou
    • Option Strictest désactivé et initial_valuea une conversion de rétrécissement en final_type.

Si Option Explicitest désactivé, les variables ne nécessitent pas de déclaration explicite ; ils sont déclarés implicitement lorsqu'ils sont utilisés :

name = initial_value

Imports synonym = type
Xojo Dim name «As type»« = initial_value» N / A
Python name = initial_value N / A synonym = type
CoffeeScript N / A
Argot name = initial_value; typedef struct {...} typename
Fortran tapez le nom type, PARAMETER :: name = value
PHP $name = initial_value; define("name", value);
const name = value (5.3+)
N / A
Perl «my» $name« = initial_value»; use constant name => value;
Raku «my «type»» $name« = initial_value»; «my «type»» constant name = value; ::synonym ::= type
Rubis name = initial_value Name = value synonym = type
Scala var name«: type» = initial_value val name«: type» = value type synonym = type
Windows PowerShell «[type] »$name = initial_value N / A N / A
Bash coquille name=initial_value N / A N / A
OCaml let name« : type ref» = ref value let name «: type» = value type synonym = type
F# let mutable name« : type» = value
ML standard val name« : type ref» = ref value val name «: type» = value
Haskell «name::type;» name = value type Synonym = type
En avant VARIABLE name(dans certains systèmes, utilisez à la place) 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.
Mathématique name=initial_value N / A N / A

^a Pascal a des blocs de déclaration. Voirfonctions.
^b Les types ne sont que des objets normaux, vous pouvez donc simplement les affecter.
^c En Perl, le mot-clé "my" délimite la variable dans le bloc.
^d Techniquement, cela ne déclare pas quenameest une variable mutable — en ML, tous les noms ne peuvent être liés qu'une seule fois ; au lieu de cela, il déclarenamepour pointer vers une structure de données "de référence", qui est une simple cellule mutable. La structure de données peut ensuite être lue et écrite à l'aide desopérateurs!et:=, respectivement.
^e Si aucune valeur initiale n'est donnée, une valeur invalide est automatiquement assignée (ce qui déclenchera une exception d'exécution si elle est utilisée avant qu'une valeur valide n'ait été assignée). Bien que ce comportement puisse être supprimé, il est recommandé dans l'intérêt de la prévisibilité. Si aucune valeur invalide ne peut être trouvée pour un type (par exemple dans le cas d'un type entier sans contrainte), une valeur valide mais prévisible est choisie à la place.
^f Dans Rust, si aucune valeur initiale n'est donnée à unevariableletoulet mutet qu'elle n'est jamais affectée ultérieurement, il y a unavertissement "variable inutilisée". Si aucune valeur n'est fournie pour unevariableconstoustaticoustatic mut, il y a une erreur. Il y a uneerreur"globalesnon majuscules"pour lesconstvariablesnon majuscules. Une fois définie, unestatic mutvariable ne peut être affectée que dans ununsafebloc ou une fonction.

Flux de contrôle

conditionnelles déclarations

si sinon si sélectionner le cas expression conditionnelle
Ada
if condition then
  statements
«else
  statements»
end if
if condition1 then
  statements
elsif 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
 )

ou alors

 (case expression is
   when value_list1 => expression1
   when value_list2 => expression2
   ...
   «when others => expressionn»
)
Graine7
if condition then
  statements
«else
  statements»
end if

si condition 1 alors

  statements
elsif condition2 then
  statements
...
«else
  statements»
end if
case expression of
  when set1 : statements
  ...
  «otherwise: statements»
end case
Module-2
if condition then
  statements
«else
  statements»
end
if condition1 then
  statements
elsif 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
(forme abrégée)
( 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:valueIfTruevalueIfFalse}
C (C99) et :
  • Objectif c
  • C++ (LIST)
  • Java
  • JavaScript
  • PHP
if (condition) instructions
«else instructions»

instructions peut être une seule instruction ou un bloc sous la forme de : { statements }

if (condition) instructions
else if (condition) instructions
...
«else instructions»

ou alors

if (condition) instructions
else { if (condition) instructions }
switch (variable) {
  case case1: instructions «; break;»
  ...
  «default: instructions»
}
condition ? valueIfTrue : valueIfFalse
C#
if (condition) instructions
«else instructions»

instructions peut être une seule instruction ou un bloc sous la forme de : { statements }

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

Tous les cas non vides doivent se terminer par une instruction breakou goto case(c'est-à-dire qu'ils ne sont pas autorisés à passer au cas suivant). L' defaultaffaire n'est pas obligée de passer en dernier.

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 }»}
Va
if condition {instructions}
«else {instructions}»
if condition {instructions}
else if condition {instructions}
...
«else {instructions}»

ou alors

switch {
  case condition: instructions
  ...
  «default: instructions»
}
switch variable {
  case case1: instructions
  ...
  «default: instructions»
}
Rapide
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}»

ou alors

unless (notcondition) {instructions}
«else {instructions}»
if (condition) {instructions}
elsif (condition) {instructions}
...
«else {instructions}»

ou alors

unless (notcondition) {instructions}
elsif (condition) {instructions}
...
«else {instructions}»
use feature "switch";
...
given (variable) {
  when (case1) { instructions }
  ...
  «default { instructions }»
}
condition ? valueIfTrue : valueIfFalse
Raku
if condition {instructions}
«else {instructions}»

ou alors

unless notcondition {instructions}
if condition {instructions} 
elsif condition {instructions} 
...
«else {instructions}
given variable {
  when case1 { instructions }
  ...
  «default { instructions }»
}
condition ?? valueIfTrue !! valueIfFalse
Rubis
if condition
  instructions
«else
  instructions»
if condition
  instructions
elsif 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»
}
if (condition) valueIfTrue else valueIfFalse
Petite conversation
condition ifTrue:
  trueBlock
«ifFalse:
  falseBlock»
end
condition ifTrue: trueBlock ifFalse: falseBlock
Lisp commun
(when condition
  instructions)

ou alors

(unless condition
  instructions)

ou alors

(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)

ou alors

(cond (test1 value1) (test2 value2) ...))
Schème
(when condition instructions)

ou alors

(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
  instructions
end
«else begin
  instructions
end»
if condition then begin
  instructions
end
else if condition then begin
  instructions
end
...
«else begin
  instructions
end»
case variable of
  case1: instructions
  ...
  «else: instructions»
end
Visual Basic
If condition Then
  instructions
«Else
  instructions»
End If

Monoligne, quand instructionssont : instruction1 : instruction2 : ...

If condition Then instructions «Else instructions»
If condition Then
  instructions
ElseIf condition Then
  instructions
...
«Else
  instructions»
End If

Une seule ligne:

Voir la note sur les langages de type C ; la Elseclause d'une Ifinstruction monoligne peut contenir une autre Ifinstruction monoligne.

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
if condition :
Tab ↹ instructions
«else:
Tab ↹ instructions»
if condition :
Tab ↹ instructions
elif condition :
Tab ↹ instructions
...
«else:
Tab ↹ instructions»
Python 3.10+ :
match variable:
Tab ↹ case case1:
Tab ↹Tab ↹ instructions
Tab ↹ case case2:
Tab ↹Tab ↹ instructions
Python 2.5+ :
valueIfTrue if condition else valueIfFalse
Argot 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
  instructions
ELSE
  instructions
ENDIF
IF (condition) THEN 
  instructions
ELSEIF (condition) THEN
  instructions
...
ELSE
  instructions
ENDIF
SELECT CASE(variable)
  CASE (case1)
    instructions
  ...
  CASE DEFAULT
    instructions
END SELECT
En avant condition IF instructions « ELSE instructions» THEN condition IF instructions ELSE condition IF instructions THEN THEN
value CASE
  case OF instructions ENDOF
  case OF instructions ENDOF
    default instructions
ENDCASE
condition IF valueIfTrue ELSE valueIfFalse THEN
OCaml if condition then begin instructions end «else begin instructions end» if condition then begin instructions end else if condition then begin instructions end ... «else begin instructions end»
match value with 
  pattern1 -> expression
  | pattern2 -> expression
  ...
  «| _ -> expression»
if condition then valueIfTrue else valueIfFalse
F# Mode de syntaxe légère :

Soit sur une seule ligne, soit avec une indentation comme indiqué ci-dessous :

if condition then
Tab ↹ instructions
«else
Tab ↹ instructions»

Mode de syntaxe verbeuse :

Identique au ML standard (ci-dessous).

Mode de syntaxe légère :

Soit sur une seule ligne, soit avec une indentation comme indiqué ci-dessous :

if condition then
Tab ↹ instructions
elif condition then
Tab ↹ instructions
...
«else
Tab ↹ instructions»

Mode de syntaxe verbeuse :

Identique au ML standard (ci-dessous).

ML standard
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»
Haskell (GHC)
if condition then expression else expression

ou alors

when condition (do instructions)

ou alors

unless notcondition (do instructions)
result | condition = expression
  | condition = expression
  | otherwise = expression
case value of {
  pattern1 -> expression;
  pattern2 -> expression;
  ...
  «_ -> expression»
}
Bash coquille
if condition-command; then
  expression
«else
  expression»
fi
if condition-command; then
  expression
elif condition-command; then
  expression
«else
  expression»
fi
case "$variable" in
  "$condition1" )
    command...
  "$condition2" )
    command...
esac
CoffeeScript
if condition then expression «else expression»

ou alors

if condition
  expression
«else
  expression»

ou alors

expression if condition

ou alors

unless condition
  expression
«else
  expression»

ou alors

expression unless condition
if condition then expression else if condition then expression «else expression»

ou alors

if condition
  expression
else if condition
  expression
«else
  expression»

ou alors

unless condition
  expression
else unless condition
  expression
«else
  expression»
switch expression
  when condition then expression
  else expression

ou alors

switch expression
  when condition
    expression
  «else
    expression»
Toutes les conditions sont des expressions.
COBOL
IF condition «THEN»
  expression
«ELSE
  expression».
EVALUATE expression «ALSO expression...»
  WHEN case-or-condition «ALSO case-or-condition...»
    expression
  ...
  «WHEN OTHER
    expression»
END-EVALUATE
Rouiller
if condition {
  expression 
}« else {
  expression 
}»
if condition {
  expression 
} else if condition {
  expression 
}« else {
  expression 
}»
match variable {
   pattern1 => expression,
   pattern2 => expression,
   pattern3 => expression,
  «_ => expression»
}

Toutes les conditions sont des expressions

si sinon si sélectionner le cas expression conditionnelle

^a Une seule instruction peut être écrite sur la même ligne après les deux points. Plusieurs instructions sont regroupées dans unblocqui commence sur une nouvelle ligne (l'indentation est obligatoire). La syntaxe de l'expression conditionnelle ne suit pas cette règle.
^b Il s'agit d'une correspondance de modèleet est similaire à la casse sélectionnée mais pas la même. Il est généralement utilisé pour déconstruiredes types de données algébriques.
^c Dans les langues de la famille Pascal, le point-virgule ne fait pas partie de l'instruction. C'est un séparateur entre les instructions, pas un terminateur.
^d END-IF peut être utilisé à la place du point à la fin.
^e Dans Rust, la virgule,à la fin d'un bras de correspondance peut être omise après le dernier bras de correspondance, ou après tout bras de correspondance dans lequel l'expression est un bloc (se termine par des crochets correspondants éventuellement vides{}).

Instructions de boucle

tandis que faire pendant pour i = du premier au dernier pour chaque
Ada
while condition loop
  statements
end loop
loop
  statements
  exit when not condition
end loop
for index in «reverse» [first .. last | discrete_type] loop
  statements
end loop
for item of «reverse» iterator loop
  statements
end loop

ou alors

(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»
  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 peut être une seule instruction ou un bloc sous la forme de : { statements }
while (condition) instructions
do instructions while (condition);
for («type» i = first; i <= last; i++) instructions
N / A
Objectif c
for (type item in set) instructions
C++ (LIST)
«std::»for_each(start, end, function)

Depuis C++11 :

for (type item : set) instructions
C#
foreach (type item in set) instructions
Java
for (type item : set) instructions
JavaScript
for (var i = first; i <= last; i++) instructions

Depuis EcmaScript 2015 :

for (var item of set) instructions
PHP
foreach (range(first, last) as $i) instructions

ou alors

for ($i = first; $i <= last; $i++) instructions
foreach (set as item) instructions

ou alors

foreach (set as key => item) instructions
Windows PowerShell
for ($i = first; $i -le last; $i++) instructions
foreach (item in set) instructions
foreach (i; first ... last) instructions
foreach («type» item; set) instructions
Va
for condition { instructions }
for i := first; i <= last; i++ { instructions }
for key, item := range set { instructions }
Rapide
while condition { instructions }
2.x :
repeat { instructions } while condition

1 fois:

do { instructions } while condition
for i = first ... last { instructions }

ou alors

for i = first ..< last+1 { instructions }

ou alors

for var i = first; i <= last; i++ { instructions }
for item in set { instructions }
Perl
while (condition) { instructions }

ou alors

until (notcondition) { instructions }

do { instructions } while ( condition ) ou

do { instructions } until (notcondition)
for«each» «$i» (first .. last) { instructions }

ou alors

for ($i = first; $i <= last; $i++) { instructions }
for«each» «$item» (set) { instructions }
Raku
while condition { instructions }

ou alors

until notcondition { instructions }
repeat { instructions } while condition

ou alors

repeat { instructions } until notcondition
for  first..last -> $i  { instructions }

ou alors

loop ($i = first; $i <=last; $i++) { instructions }
for set« -> $item»  { instructions }
Rubis
while condition
  instructions
end

ou alors

until notcondition
  instructions
end
begin
  instructions
end while condition

ou alors

begin
  instructions
end until notcondition
for i in first..last
  instructions
end

ou alors

for i in first...last+1
  instructions
end

ou alors

first.upto(last) { ||i|| instructions }
for item in set
  instructions
end

ou alors

set.each { |item| instructions }
Bash coquille
while condition ;do
  instructions
done

ou alors

until notcondition ;do
  instructions
done
N / A
for ((i = first; i <= last; ++i)) ; do
  instructions
done
for item in set ;do
  instructions
done
Scala
while (condition) { instructions }
do { instructions } while (condition)
for (i <- first to last «by 1») { instructions }

ou alors

first to last «by 1» foreach (i => { instructions })
for (item <- set) { instructions }

ou alors

set foreach (item => { instructions })
Petite conversation
conditionBlock whileTrue:
  loopBlock
loopBlock doWhile:
  conditionBlock
first to: last do:
  loopBlock
collection do:
  loopBlock
Lisp commun
(loop
  while condition
  do
  instructions)

ou alors

(do () (notcondition)
  instructions)
(loop
  do
  instructions
  while condition)
(loop
  for i from first to last «by 1»
  do
  instructions)

ou alors

(dotimes (i N)
  instructions)

ou alors

(do ((i first (1+ i))) ((>=i last))
  instructions)
(loop
  for item in list
  do
  instructions)

ou alors

(loop
  for item across vector
  do
  instructions)

ou alors

(dolist (item list)
  instructions)

ou alors

(mapc function list)

ou alors

(map 'type function sequence)
Schème
(do () (notcondition) instructions)

ou alors

(let loop () (if condition (begin instructions (loop))))
(let loop () (instructions (if condition (loop))))
(do ((i first (+ i 1))) ((>= i last)) instructions)

ou alors

(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
  instructions
end
repeat
  instructions
until notcondition;
for i := first «step 1» to last do begin
  instructions
end;
for item in set do instructions
Visual Basic
Do While condition
  instructions
Loop

ou alors

Do Until notcondition
  instructions
Loop

ou alors

While condition
  instructions
Wend (Visual Basic .NET uses End While instead)
Do
  instructions
Loop While condition

ou alors

Do
  instructions
Loop Until notcondition
i doit être déclaré au préalable.
For i = first To last «Step 1»
  instructions
Next i
For Each item In set
  instructions
Next item
Visual Basic .NET
For i« As type» = first To last« Step 1»
  instructions
Next« i»
For Each item« As type» In set
  instructions
Next« item»
Xojo
While condition
  instructions
Wend
Do Until notcondition
  instructions
Loop

ou alors

Do
  instructions
Loop Until notcondition
Python
while condition :
Tab ↹ instructions
«else:
Tab ↹ instructions»
N / A Python 3.x :
for i in range(first, last+1):
Tab ↹ instructions
«else:
Tab ↹ instructions»

Python 2.x :

for i in xrange(first, last+1):
Tab ↹ instructions
«else:
Tab ↹instructions»
for item in set:
Tab ↹ instructions
«else:
Tab ↹ instructions»
Argot
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)
  instructions
ENDDO
DO
  instructions
   IF (condition) EXIT
ENDDO
DO I = first,last
  instructions
ENDDO
N / A
En avant
BEGIN « instructions » condition WHILE instructions REPEAT
BEGIN  instructions condition UNTIL
limit start DO instructions LOOP
N / A
OCaml
while condition do instructions done
N / A
for i = first to last do instructions done
Array.iter (fun item -> instructions) array

ou alors

List.iter (fun item -> instructions) list
F#
while condition do
Tab ↹ instructions
N / A
for i = first to last do
Tab ↹ instructions
for item in set do
Tab ↹ instructions

ou alors

Seq.iter (fun item -> instructions) set
ML standard
while condition do ( instructions )
N / A
Array.app (fn item => instructions) array

ou alors

app (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
  setup
until
  condition
loop
  instructions
end
CoffeeScript
while condition
  expression

ou alors

expression while condition

ou alors

while condition then expression

ou alors

until condition
  expression

ou alors

expression until condition

ou alors

until expression then condition
N / A
for i in [first..last]
  expression

ou alors

for i in [first..last] then expression

ou alors

expression for i in [first..last]
for item in set
  expression

ou alors

for item in set then expression

ou alors

expression for item in set
COBOL
PERFORM procedure-1 «THROUGH procedure-2» ««WITH» TEST BEFORE» UNTIL condition

ou alors

PERFORM ««WITH» TEST BEFORE» UNTIL condition
  expression
END-PERFORM
PERFORM procedure-1 «THROUGH procedure-2» «WITH» TEST AFTER UNTIL condition

ou alors

PERFORM «WITH» TEST AFTER UNTIL condition
  expression
END-PERFORM
PERFORM procedure-1 «THROUGH procedure-2» VARYING i FROM first BY increment UNTIL i > last

ou alors

PERFORM VARYING i FROM first BY increment UNTIL i > last
  expression
END-PERFORM
N / A
Rouiller
while condition {
  expression
}
loop {
  expression
  if condition {
      break;
  }
}
for i in first..last+1 {
  expression
}

ou alors

for i in first..=last {
  expression
} 
for item in set {
  expression
}

ou alors

set.into_iter().for_each(|item| expression);

^a "stepn" est utilisé pour changer l'intervalle de boucle. Si "step" est omis, alors l'intervalle de boucle est 1.

^b Ceci implémente lequantificateur universel("pour tous" ou "∀") ainsi que lequantificateur existentiel("il existe" ou "∃").

^c THRU peut être utilisé à la place deTHROUGH.

^d peut être utilisé à la place de. «IS» GREATER «THAN»>

^e Le type d'expression d'ensemble doit implémenter traitstd::iter::IntoIterator.

Exceptions

lancer gestionnaire affirmation
Ada raise exception_name «with string_expression» begin
statements
exception
when exception_list1 => statements;
when exception_list2 => statements;
...
«when others => statements;»
end
pragma Assert («Check =>» boolean_expression ««Message =>» string_expression»)

[function | procedure | entry] with
Pre => boolean_expression
Post => boolean_expression

any_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);ou alors

System.Diagnostics.Trace.Assert(condition);

Java try { instructions } catch (exception) { instructions } ... «finally { instructions }» assert condition «: description»;
JavaScript try { instructions } catch (exception) { instructions } «finally { instructions }» ?
try { instructions } catch (exception) { instructions } ... «finally { instructions }» assert(condition);
PHP try { instructions } catch (exception) { instructions } ... «finally { instructions }» assert(condition);
Argot try { instructions } catch «exception» { instructions } ... «finally { instructions }» ?
Windows PowerShell trap «[exception]» { instructions } ... instructions or try { instructions } catch «[exception]» { instructions } ... «finally { instructions }» [Debug]::Assert(condition)
Objectif c @throw exception; @try { instructions } @catch (exception) { instructions } ... «@finally { instructions }» NSAssert(condition, description);
Rapide 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 } ...}} ?
Rubis raise exception begin
instructions
rescue exception
instructions
...
«else
instructions»
«ensure
instructions»
end
Petite conversation exception raise instructionBlock on: exception do: handlerBlock assert: conditionBlock
Lisp commun (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»))
...)
(assert condition) or
(assert condition
«(place)
«error»»)
or
(check-type var type)
Schéma (R 6 RS) (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
instructions
End Select: End With
'*** Try class ***
Private mstrDescription As String
Private mlngNumber As Long

Public Sub Catch()
    mstrDescription = Err.Description
    mlngNumber = Err.Number
End Sub

Public Property Get Number() As Long
    Number = mlngNumber
End Property

Public Property Get Description() As String
    Description = mstrDescription
End Property
Debug.Assert condition
Visual Basic .NET Throw exceptionou alors

Error errorcode

Try
instructions
Catch« name As exception»« When condition»
instructions
...
«Finally
instructions»
End Try
System.Diagnostics.Debug.Assert(condition)ou alors

System.Diagnostics.Trace.Assert(condition)

Xojo Raise exception Try
instructions
Catch «exception»
instructions
...
«Finally
instructions»
End Try
N / A
Python raise exception try:
Tab ↹ instructions
except «exception»:
Tab ↹ instructions
...
«else:
Tab ↹ instructions»
«finally:
Tab ↹ instructions»
assert condition
Fortran N / A
En avant 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 ...
or
try expression finally expression
ML standard raise exception «arg» expression handle pattern => expression ...
Haskell (GHC) throw exception
or
throwError expression
catch tryExpression catchExpression
or
catchError tryExpression catchExpression
assert condition expression
COBOL RAISE «EXCEPTION» exception USE «AFTER» EXCEPTION OBJECT class-name. or
USE «AFTER» EO class-name. or
USE «AFTER» EXCEPTION CONDITION exception-name «FILE file-name». or
USE «AFTER» EC exception-name «FILE file-name».
N / A
Rouiller Non assert!(condition)

^a Common Lisp permetwith-simple-restart,restart-caseetrestart-bindde définir des redémarrages à utiliser avecinvoke-restart. Des conditions non gérées peuvent amener l'implémentation à afficher un menu de redémarrage à l'utilisateur avant de dérouler la pile.

^b Les exceptions non interceptées sont propagées à l'exécution la plus interne englobant dynamiquement. Les exceptions ne sont pas propagées entre les tâches (sauf si ces tâches sont actuellement synchronisées dans un rendez-vous).


Autres instructions de flux de contrôle

bloc de sortie (pause) Continuez étiqueter branche ( aller à ) valeur de retour du générateur
Ada 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)

( Rappel )

APL :Leave :Continue label: label
or
:GoTo label
N / A
C (C99) break; continue; label: goto label; N / A
Objectif c
C++ (LIST)
C# yield return value;
Java break «label»; continue «label»; N / A
JavaScript yield value«;»
PHP break «levels»; continue «levels»; goto label; yield «key =>» value;
Perl last «label»; next «label»;
Raku
Va break «label» continue «label» goto label
Rapide break «label» continue «label» N / A
Bash coquille break «levels» continue «levels» N / A N / A N / A
Lisp commun (return) or
(return-from block) or
(loop-finish)
(tagbody tag
...
tag
...)
(go tag)
Schème
ISLISP (return-from block) (tagbody tag
...
tag
...)
(go tag)
Pascal (ISO) N / A label: goto label; N / A
Pascal (FPC) break; continue;
Visual Basic Exit blockAlternativement, pour les méthodes,

Return

N / A label: GoTo label
Xojo Continue block
Visual Basic .NET Yield value
Python break continue N / A yield value
RPG IV LEAVE; ITER;
Argot break; continue;
Fortran EXIT CYCLE label GOTO label N / A
Rubis break next
Windows PowerShell break «label» continue
OCaml N / A
F#
ML standard
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 a des blocs de déclaration. Voirfonctions.
L' étiquette ^b doit être un nombre compris entre 1 et 99999.

Les fonctions

Voir la réflexion pour appeler et déclarer des fonctions par des chaînes.

appeler une fonction fonction de base/vide fonction de retour de valeur fonction principale requise
Ada 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
}
Objectif c
C++ (LIST)
Java public static void main(String[] args) { instructions } or
public static void main(String... args) { instructions }
int main(«char[][] args») { instructions} or
int main(«string[] args») { instructions} or
void main(«char[][] args») { instructions} or
void main(«string[] args») { instructions}
C# Comme ci-dessus; alternativement, s'il n'y a qu'une seule déclaration :

void foo(«parameters») => statement;

Comme ci-dessus; alternativement, si assez simple pour être une expression :

void foo(«parameters») => expression;

static void Main(«string[] args») method_body

Peut à la place revenir int.

(à partir de C# 7.1 :) Peut retourner Taskou Task<int>, et si c'est le cas, peut être async.

JavaScript function foo(«parameters») { instructions } or
var foo = function («parameters») {instructions } or
var foo = new Function («"parameter", ... ,"last parameter"» "instructions");
function foo(«parameters») { instructions ... return value; } N / A
Va func foo(«parameters») { instructions } func foo(«parameters») type { instructions ... return value } func main() { instructions }
Rapide func foo(«parameters») { instructions } func foo(«parameters») -> type { instructions ... return value } N / A
Lisp commun (foo «parameters») (defun foo («parameters»)
instructions)
or
(setf (symbol-function 'symbol)
function)
(defun foo («parameters»)
...
value)
N / A
Schème (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;»
«label
label declarations»
«const
constant declarations»
«type
type declarations»
«var
variable declarations»
«local function declarations»
begin
instructions
end;
function foo«(parameters)»: type; «forward;»
«label
label declarations»
«const
constant declarations»
«type
type declarations»
«var
variable declarations»
«local function declarations»
begin
instructions;
foo :=
value
end;
program name;
«label
label declarations»
«const
constant declarations»
«type
type declarations»
«var
variable declarations»
«function declarations»
begin
instructions
end.
Visual Basic Foo(«parameters») Sub Foo«(parameters)»
instructions
End Sub
Function Foo«(parameters)»« As type»
instructions
Foo = value
End Function
Sub Main()
instructions
End Sub
Visual Basic .NET Comme ci-dessus; alternativement : Function Foo«(parameters)»« As type»
instructions
Return value
End Function


La Asclause n'est pas requise si Option Strictest désactivé. Un caractère type peut être utilisé à la place de la Asclause.

Si le contrôle quitte la fonction sans qu'une valeur de retour ait été explicitement spécifiée, la fonction renvoie la valeur par défaut pour le type de retour.

Sub Main(««ByVal »args() As String»)
instructions
End Sub
ou alors Function Main(««ByVal »args() As String») As Integer
instructions
End Function
Xojo
Python foo(«parameters») def foo(«parameters»):
Tab ↹ instructions
def foo(«parameters»):
Tab ↹ instructions
Tab ↹ return value
N / A
Argot 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»)
SUBROUTINE sub_foo («arguments»)
instructions
END SUBROUTINE
type FUNCTION foo («arguments»)
instructions
...
foo = value
END FUNCTION
PROGRAM main
instructions
END PROGRAM
En avant «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; }
Rubis foo«(parameters)» def foo«(parameters)»
instructions
end
def foo«(parameters)»
instructions
«return» value
end
Rouiller 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 };
or
function foo { «param(parameters)» instructions }
function foo «(parameters)» { instructions return value }; or
function foo { «param(parameters)» instructions return value }
N / A
Bash coquille foo «parameters»

function foo {
    instructions
}
ou alors
foo () {
    instructions
}

function foo {
    instructions
    return «exit_code»
}
ou alors
foo () {
    instructions
    return «exit_code»
}

  • paramètres
    • $n( 1 $ , 2 $ , 3 $ , ...)
    • $@ (tous les paramètres)
    • $# (le nombre de paramètres)
    • $0 (ce nom de fonction)
OCaml foo parameters let «rec» foo parameters = instructions let «rec» foo parameters = instructions... return_value
F# [<EntryPoint>] let main args = instructions
ML standard fun foo parameters = ( instructions ) fun foo parameters = ( instructions... return_value )
Haskell foo parameters = do
Tab ↹ instructions
foo parameters = return_value
or
foo parameters = do
Tab ↹ instructions
Tab ↹ return value
«main :: IO ()»
main = do instructions
Eiffel foo («parameters») foo («parameters»)
require
preconditions
do
instructions
ensure
postconditions
end
foo («parameters»): type
require
preconditions
do
instructions
Result := value
ensure
postconditions
end
CoffeeScript foo() foo = -> foo = -> value N / A
foo parameters foo = () -> foo = ( parameters ) -> value
COBOL CALL "foo" «USING parameters»
«exception-handling»
«END-CALL»
«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 requiert "forward;" pourles déclarations directes.
^b Eiffel permet de spécifier la classe racine et la fonctionnalité d'une application.
^c En Fortran, les paramètres de fonction/sous-routine sont appelés arguments (puisqu'ilPARAMETERs'agit d'un mot-clé du langage) ; leCALLmot-clé est requis pour les sous-routines.
^d Au lieu d'utiliser"foo", une variable de chaîne peut être utilisée à la place contenant la même valeur.

Conversions de type

chaîne est un nombre décimal signé :

chaîne en entier chaîne en entier long chaîne en virgule flottante entier en chaîne virgule flottante en chaîne
Ada Integer'Value (string_expression) Long_Integer'Value (string_expression) Float'Value (string_expression) Integer'Image (integer_expression) Float'Image (float_expression)
ALGOL 68 avec des formats généraux, puis spécifiques Avec déclarations préalables et association de : 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));
ou alors
getf(proxy, ($dddd$, ivar));
getf(proxy, ($g$, livar));
ou alors
getf(proxy, ($8d$, livar));
getf(proxy, ($g$, rvar));
ou alors
getf(proxy, ($8d.4dE2d$, rvar));
putf(proxy, ($g$, ival));
ou alors
putf(proxy, ($4d$, ival));
putf(proxy, ($g(width, places, exp)$, rval));
ou alors
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);
Objectif c integer = [string intValue]; long = [string longLongValue]; float = [string doubleValue]; string = [NSString stringWithFormat:@"%i", integer]; string = [NSString stringWithFormat:@"%f", float];
C++ (LIST) «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(string); long = long.Parse(string); float = float.Parse(string); double = double.Parse(string); string = number.ToString();
integer = std.conv.to!int(string) long = std.conv.to!long(string) float = std.conv.to!float(string) double = std.conv.to!double(string) string = std.conv.to!string(number)
Java integer = Integer.parseInt(string); long = Long.parseLong(string); float = Float.parseFloat(string);
double = Double.parseDouble(string);
string = Integer.toString(integer); string = String.valueOf(integer); string = Float.toString(float); string = Double.toString(double);
JavaScript 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}`
Va integer, error = strconv.Atoi(string)
integer, error = strconv.ParseInt(string, 10, 0)
long, error = strconv.ParseInt(string, 10, 64) float, error = strconv.ParseFloat(string, 64) string = strconv.Itoa(integer) string = strconv.FormatInt(integer, 10)

string = fmt.Sprint(integer)

string = strconv.FormatFloat(float) string = fmt.Sprint(float)
Rouiller 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()
Lisp commun (setf integer (parse-integer string)) (setf float (read-from-string string)) (setf string (princ-to-string number))
Schème (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)
double = CDbl(string)
string = CStr(number)
Visual Basic .NET

(peut utiliser à la fois la syntaxe VB ci-dessus

et méthodes .NET illustrées à droite)

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) or string = Str(number)
Python integer = int(string) long = long(string) float = float(string) string = str(number)
Argot 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 number = 0 + string; string = "number";
Raku number = +string; string = ~number;
Rubis 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
Petite conversation 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_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
ML standard 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) TO number MOVE number TO numeric-edited

^a JavaScript n'utilise que des nombres à virgule flottante, il y a donc quelques détails techniques.
^b Perl n'a pas de types séparés. Les chaînes et les chiffres sont interchangeables.
^c NUMVAL-C ouNUMVAL-Fpeut être utilisé à la place deNUMVAL.
^ str::parse est disponible pour convertir tout type ayant une implémentation dustd::str::FromStrtrait. Les deuxstr::parseetFromStr::from_strrenvoient unResultqui contient le type spécifié s'il n'y a pas d'erreur. Leturbofish(::<_>) surstr::parsepeut être omis si le type peut être déduit du contexte.

E/S de flux standard

Lire de écrire à
standard sortie standard stderr
Ada 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));
APL x← ⎕←x ⍞←x
C (C99) scanf(format, &x); or
fscanf(stdin, format, &x);
printf( format, x); or
fprintf(stdout, format, x);
fprintf(stderr, format, x );
Objectif 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(); orx = Console.ReadLine(); Console.Write(«format, »x); or
Console.WriteLine(«format, »x);
Console.Error.Write(«format, »x); or
Console.Error.WriteLine(«format, »x);
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.writef(stderr, format, x) or
std.stdio.writefln(stderr, format, x)
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);
Va 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)
Rapide x = readLine() (2.x) print(x)(2.x) (1.x)
println(x)
Implémentation du navigateur Web JavaScript
document.write(x)
Pages de serveur actif JavaScript
Response.Write(x)
Hôte de scripts Windows JavaScript
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)
Lisp commun (setf x (read-line)) (princ x) or
(format t format x)
(princ x *error-output*) or
(format *error-output* format x)
Schéma (R 6 RS) (define x (read-line)) (display x) or
(format #t format x)
(display x (current-error-port)) or
(format (current-error-port) format x)
ISLISP (setf x (read-line)) (format (standard-output) format x) (format (error-output) format x)
Pascal read(x); or
readln(x);
write(x); or
writeln(x);
write(stderr, x); or
writeln(stderr, x);
Visual Basic Input« prompt,» x Print x or
? x
N / A
Visual Basic .NET x = Console.Read() or
x = Console.ReadLine()
Console.Write(«format, »x) or
Console.WriteLine(«format, »x)
Console.Error.Write(«format, »x) or
Console.Error.WriteLine(«format, »x)
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)
print >> sys.stderr, x or
sys.stderr.write(x)
Python 3.x x = input(«prompt») print(, end=""») print(, end=""», file=sys.stderr)
Argot fgets (&x, stdin) fputs (x, stdout) fputs (x, stderr)
Fortran READ(*,format) variable names or
READ(INPUT_UNIT,
format) variable names
WRITE(*,format) expressions or
WRITE(OUTPUT_UNIT,
format) expressions
WRITE(ERROR_UNIT,format) expressions
En avant buffer length ACCEPT ( # chars read )
KEY ( char )
buffer length TYPE
char EMIT
N / A
PHP $x = fgets(STDIN); or
$x = fscanf(STDIN, format);
print x; or
echo x; or
printf(format, x);
fprintf(STDERR, format, x);
Perl $x = <>; or
$x = <STDIN>;
print x; or
printf format, x;
print STDERR x; or
printf STDERR format, x;
Raku $x = $*IN.get; x.print or
x.say
x.note or
$*ERR.print(x) or
$*ERR.say(x)
Rubis 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 ...
ML standard val str = TextIO.inputLIne TextIO.stdIn print str TextIO.output (TextIO.stdErr, str)
Haskell (GHC) x <- readLn or
str <- getLine
print x or
putStrLn str
hPrint stderr x or
hPutStrLn stderr str
COBOL ACCEPT x DISPLAY x


^a ALGOL 68 en plus commeroutines detransput"non formatées":et. ^b etlisez le texte non formaté de stdin. L'utilisation de get n'est pas recommandée. ^c etécrivez du texte non formaté sur stdout. ^d écrit du texte non formaté sur stderr ^e sont définis dans lemodule. read, write, getput
gets(x)fgets(x, length, stdin)
puts(x)fputs(x, stdout)
fputs(x, stderr)
INPUT_UNIT, OUTPUT_UNIT, ERROR_UNITISO_FORTRAN_ENV

Lecture des arguments de ligne de commande

Valeurs des arguments L'argument compte Nom du programme / Nom du script
Ada Argument (n) Argument_Count Command_Name
C (C99) argv[n] argc premier argument
Objectif c
C++
C# args[n] args.Length Assembly.GetEntryAssembly().Location;
Java args.length
premier argument
JavaScript
Windows Script Host mise en œuvre
WScript.Arguments(n) WScript.Arguments.length WScript.ScriptName or WScript.ScriptFullName
Va os.Args[n] len(os.Args) premier argument
Rouiller 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()
Rapide Process.arguments[n] ou alors
Process.unsafeArgv[n]
Process.arguments.count ou alors
Process.argc
premier argument
Lisp commun ? ? ?
Schéma (R 6 RS) (list-ref (command-line) n) (length (command-line)) premier argument
ISLISP N / A N / A N / A
Pascal ParamStr(n) ParamCount premier argument
Visual Basic Command N / A App.Path
Visual Basic .NET CmdArgs(n) CmdArgs.Length [Assembly].GetEntryAssembly().Location
Xojo System.CommandLine (analyse de chaîne) Application.Executable.Name
Python sys.argv[n] len(sys.argv) premier argument
Argot __argv[n] __argc premier argument
Fortran DO i = 1,argc
CALL GET_COMMAND_ARGUMENT (i,argv(i))
ENDDO
argc = COMMAND_ARGUMENT_COUNT () CALL GET_COMMAND_ARGUMENT (0,progname)
PHP $argv[n] $argc premier argument
Bash coquille $n ($1, $2, $3, ...)
$@ (tous les arguments)
$# $0
Perl $ARGV[n] scalar(@ARGV) $0
Raku @*ARGS[n] @*ARGS.elems $PROGRAM_NAME
Rubis ARGV[n] ARGV.size $0
Windows PowerShell $args[n] $args.Length $MyInvocation.MyCommand.Name
OCaml Sys.argv.(n) Array.length Sys.argv premier argument
F# args.[n] args.Length Assembly.GetEntryAssembly().Location
ML standard 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 N / A
  • ^a Dans Rust,std::env::argsetstd::env::args_osretournent les itérateurs,std::env::Argsetstd::env::ArgsOsrespectivement. Argsconvertit chaque argument en aStringet il panique s'il atteint un argument qui ne peut pas être converti enUTF-8. ArgsOsrenvoie une représentation sans perte des chaînes brutes du système d'exploitation (std::ffi::OsString), qui peut être un UTF-8 non valide.
  • ^b En Visual Basic, les arguments de ligne de commande ne sont pas séparés. Les séparer nécessite une fonction de division.Split(string)
  • ^c La norme COBOL n'inclut aucun moyen d'accéder aux arguments de ligne de commande, mais les extensions de compilateur courantes pour y accéder incluent la définition de paramètres pour le programme principal ou lesACCEPTinstructions d'utilisation.

Exécution de commandes

Commande Shell Exécuter le programme Remplacer le programme actuel par le nouveau programme exécuté
Ada Ne fait pas partie de la norme linguistique. Généralement effectué par des packages fournis par le compilateur ou par interfaçage avec C ou POSIX .
C system("command"); execl(path, args); or
execv(path, arglist);
C++
Objectif c [NSTask launchedTaskWithLaunchPath:(NSString *)path arguments:(NSArray *)arguments];
C# System.Diagnostics.Process.Start(path, argstring);
F#
Va 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.Interaction.Shell(command «WindowStyle» «isWaitOnReturn») System.Diagnostics.Process.Start(path, argstring)
Xojo Shell.Execute(command «Parameters») FolderItem.Launch(parameters, activate) N / A
std.process.system("command"); std.process.execv(path, arglist);
Java Runtime.exec(command); or
new ProcessBuilder(command).start();
JavaScript
Windows Script Host mise en œuvre
WScript.CreateObject ("WScript.Shell").Run(command «WindowStyle» «isWaitOnReturn»); WshShell.Exec(command)
Lisp commun (uiop:run-program command)
Schème (system command)
ISLISP N / A N / A N / A
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
ML standard OS.Process.system command Unix.execute (path, args) Posix.Process.exec (path, args)
Haskell (GHC) System.system command System.Process.runProcess path args ... Posix.Process.executeFile path True args ...
Perl system(command) or
$output = `command` or
$output = qx(command)
exec(path, args)
Rubis 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)
Argot system(command)
Fortran CALL EXECUTE_COMMAND_LINE (COMMAND «, WAIT» «, EXITSTAT» «, CMDSTAT» «, CMDMSG»)
Windows PowerShell [Diagnostics.Process]::Start(command) «Invoke-Item »program arg1 arg2 …
Bash coquille output=`command` ou alors

output=$(command)

program arg1 arg2 …

^ un Fortran 2008 ou plus récent.

Les références