Porównanie języków programowania (podstawowe instrukcje) - Comparison of programming languages (basic instructions)

W tym artykule porównano dużą liczbę języków programowania przez zestawienie ich typów danych , składni wyrażeń , instrukcji i deklaracji oraz niektórych typowych interfejsów systemu operacyjnego.

Konwencje tego artykułu

Pogrubienie jest kod dosłowne. Nie pogrubienie jest interpretowane przez czytelnika. Oświadczenia w guillemetach («...») są opcjonalne. Tab ↹wskazuje niezbędne wcięcie (ze spacją).

Identyfikatory typu

Liczby całkowite

8 bitów ( bajt ) 16 bitów ( krótka liczba całkowita ) 32-bitowy 64 bity ( długa liczba całkowita ) Rozmiar słowa Dowolnie precyzyjne ( bignum )
Podpisano Niepodpisany Podpisano Niepodpisany Podpisano Niepodpisany Podpisano Niepodpisany Podpisano Niepodpisany
Ada range -2**7 .. 2**7 - 1 range 0 .. 2**8 - 1 lub mod 2**8 range -2**15 .. 2**15 - 1 range 0 .. 2**16 - 1 lub mod 2**16 range -2**31 .. 2**31 - 1 range 0 .. 2**32 - 1 lub mod 2**32 range -2**63 .. 2**63 - 1 mod 2**64 Integer range 0 .. 2**Integer'Size - 1 lub mod Integer'Size Nie dotyczy
ALGOL 68 (zmienna szerokość) short short int Nie dotyczy short int Nie dotyczy int Nie dotyczy long int Nie dotyczy int Nie dotyczy long long int
bytes & bits
C ( C99 o stałej szerokości) int8_t uint8_t int16_t uint16_t int32_t uint32_t int64_t uint64_t intptr_t size_t Nie dotyczy
C++ ( C++11 o stałej szerokości)
C ( C99 o zmiennej szerokości) signed char unsigned char short unsigned short long unsigned long long long unsigned long long int unsigned int
C++ ( C++11 o zmiennej szerokości)
Cel-C ( kakao ) 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
DO# sbyte byte short ushort int uint long ulong IntPtr UIntPtr System.Numerics.BigInteger
(.NET 4.0)
Jawa byte Nie dotyczy char Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy java.math.BigInteger
Udać się int8 uint8 lub byte int16 uint16 int32 uint32 int64 uint64 int uint big.Int
Rdza i8 u8 i16 u16 i32 u32 i64 u64 isize usize Nie dotyczy
Szybki Int8 UInt8 Int16 UInt16 Int32 UInt32 Int64 UInt64 Int UInt
re byte ubyte short ushort int uint long ulong Nie dotyczy Nie dotyczy BigInt
Wspólne seplenienie (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
Schemat
ISLISP bignum
Pascal ( FPC ) shortint byte smallint word longint longword int64 qword integer cardinal Nie dotyczy
Visual Basic Nie dotyczy Byte Integer Nie dotyczy Long Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy
Visual Basic .NET SByte Short UShort Integer UInteger Long ULong System.Numerics.BigInteger
(.NET 4.0)
FreeBasic Byte lub Integer<8> UByte lub UInteger<8> Short lub Integer<16> UShort lub UInteger<16> Long lub Integer<32> ULong lub UInteger<32> LongInt lub Integer<64> ULongInt lub UInteger<64> Integer UInteger Nie dotyczy
Python 2.x Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy int Nie dotyczy long
Python 3.x Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy int
Gwara Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy
Fortran INTEGER(KIND = n) Nie dotyczy INTEGER(KIND = n) Nie dotyczy INTEGER(KIND = n) Nie dotyczy INTEGER(KIND = n) Nie dotyczy
PHP Nie dotyczy Nie dotyczy int Nie dotyczy int Nie dotyczy Nie dotyczy
Perl 5 Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy Math::BigInt
Raku int8 uint8 int16 uint16 int32 uint32 int64 uint64 Int Nie dotyczy
Rubin Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy Fixnum Nie dotyczy Bignum
Erlang Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy liczba całkowita() Nie dotyczy liczba całkowita()
Scala Byte Nie dotyczy Short Char Int Nie dotyczy Long Nie dotyczy Nie dotyczy Nie dotyczy scala.math.BigInt
Nasiona7 Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy integer Nie dotyczy Nie dotyczy Nie dotyczy bigInteger
Pogawędka Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy SmallInteger Nie dotyczy LargeInteger
Windows PowerShell Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy
OCaml Nie dotyczy Nie dotyczy int32 Nie dotyczy int64 Nie dotyczy int
or
nativeint
open Big_int;;
big_int
FA# sbyte byte int16 uint16 int32 lub int uint32 uint64 nativeint unativeint bigint
Standardowy ML Nie dotyczy Word8.word Nie dotyczy Int32.int Word32.word Int64.int Word64.word int word LargeInt.int lub
IntInf.int
Haskella ( 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
Eiffla INTEGER_8 NATURAL_8 INTEGER_16 NATURAL_16 INTEGER_32 NATURAL_32 INTEGER_64 NATURAL_64 INTEGER NATURAL Nie dotyczy
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 Nie dotyczy Nie dotyczy Nie dotyczy
Matematyka Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy Integer
Język Wolfram Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy Nie dotyczy Integer

^ A Testandardowestałeint shortsiint lengthsmogą być wykorzystane do określenia, ile „short«S»long«s może być użytecznie prefiksem do»short int” i „long int”. Faktycznie wielkość „short int”, „int” i „long int” jest dostępny jako stałeshort max int,max intalong max intitd.
^ B Powszechnie stosowane do znaków.
^ C The Algol 68, C i C ++ języki nie została dokładnie określona szerokość typów całkowitychshort,int,longoraz (C99, C ++ 11)long long, tak, że są zależne od implementacji. W języku C i C ++short,long, ilong longtypów muszą być co najmniej 16, 32 lub 64 bitów szerokości, odpowiednio, ale może być więcej. intTyp muszą być co najmniej tak szeroka jakshorti co najwyżej tak szeroki, jaklongi zazwyczaj o szerokości równej długości słowa na procesorze urządzenia (to znaczy w urządzeniu 32-bitowym jest często 32-bitowe, na 64 -bitowych maszynach czasami ma szerokość 64 bitów). C99 i C++11 definiują również[u]intN_ttypyodokładnej szerokości wnagłówkustdint.h. Abyuzyskać więcej informacji,zobaczC składnia#Integralne typy. Ponadto typysize_tiptrdiff_tsą zdefiniowane w odniesieniu do rozmiaru adresu, aby przechowywać liczby całkowite bez znaku i ze znakiem wystarczająco duże, aby obsłużyć indeksy tablicy i różnicę między wskaźnikami.
^d Perl 5 nie ma odrębnych typów. Liczby całkowite, liczby zmiennoprzecinkowe, łańcuchy itp. są uważane za „skalary”.
^e PHP ma dwie biblioteki o dowolnej precyzji. Biblioteka BCMath używa tylko ciągów jako typu danych. Biblioteka GMP wykorzystuje wewnętrzny typ „zasobu”.
^f Wartość "n" jest dostarczana przez funkcjęSELECTED_INT_KINDwewnętrzną.
^g Opcja run timeALGOL 68G--precision "number"może ustawić precyzję dlalong long ints na wymaganą "liczbę" cyfr znaczących. Testandardowestałelong long int widthilong long max intmogą być wykorzystane do określenia rzeczywistej precyzji.
^h COBOLumożliwia określenie wymaganej precyzji i automatycznie wybierze dostępny typ, który może reprezentować określoną precyzję. PIC S9999Na przykład„” wymagałoby zmiennej ze znakiem z dokładnością do czterech cyfr dziesiętnych. Jeśli zostanie określony jako pole binarne, na większości platform zostanie wybrany 16-bitowy typ ze znakiem.
^i Smalltalkautomatycznie wybiera odpowiednią reprezentację liczb całkowitych. Zazwyczaj występują dwie reprezentacje, jedna dla liczb całkowitych pasujących do natywnego rozmiaru słowa minus dowolny bit znacznika (SmallInteger) i jedna obsługująca liczby całkowite o dowolnej wielkości (LargeInteger). Operacje arytmetyczne obsługują argumenty polimorficzne i zwracają wynik w najbardziej odpowiedniej zwartej reprezentacji.
^j Typy zakresówAdysą sprawdzane pod kątem naruszeń granic w czasie wykonywania (jak również w czasie kompilacji dla wyrażeń statycznych). Naruszenia granic w czasie wykonywania powodują wyjątek „błąd ograniczenia”. Zakresy nie są ograniczone do potęg dwójki. Powszechnie predefiniowane podtypy Integer to: Dodatni (range 1 .. Integer'Last) i Naturalny (range 0 .. Integer'Last). Short_Short_Integer(8 bitów),Short_Integer(16 bitów) iLong_Integer(64 bity) są również powszechnie predefiniowane, ale nie są wymagane przez standard Ada. Kontrole w czasie wykonywania można wyłączyć, jeśli wydajność jest ważniejsza niż sprawdzanie integralności.
^k Adatypy modulo implementują arytmetykę modulo we wszystkich operacjach, tzn. nie ma możliwości naruszenia zakresu. Moduły nie są ograniczone do potęgi dwójki.
^l Powszechnie używane dla znaków takich jak char Java.
^m int w PHP ma taką samą szerokość jaklongtyp w C w tym systemie.
^n Erlangjest wpisywany dynamicznie. Identyfikatory typu są zwykle używane do określania typów pól rekordów oraz typów argumentów i zwracanych funkcji.
^o Gdy przekracza jedno słowo.

zmiennoprzecinkowy

Pojedyncza precyzja Podwójna precyzja Inna precyzja Zależny od procesora
Ada Float Long_Float Nie dotyczy
ALGOL 68 real long real short real, long long realitd.
do float double long double
C++ (STL)
Cel-C (kakao) CGFloat
DO# float Nie dotyczy
Jawa
Udać się float32 float64
Rdza f32 f64
Szybki Float
Float32
Double
Float64
Float80 CGFloat
re float double real
Wspólne seplenienie single-float double-float float, short-float, long-float
Schemat
ISLISP
Pascal (darmowy Pascal) single double real
Visual Basic Single Double Nie dotyczy
Visual Basic .NET
Xojo
Pyton Nie dotyczy float
JavaScript Number Nie dotyczy
Gwara
Fortran REAL(KIND = n)
PHP float
Perl
Raku num32 num64 Num
Rubin Nie dotyczy Float Nie dotyczy
Scala Float Double
Nasiona7 Nie dotyczy float
Pogawędka Float Double
Windows PowerShell
OCaml Nie dotyczy float Nie dotyczy
FA# float32
Standardowy ML Nie dotyczy real
Haskella (GHC) Float Double
Eiffla REAL_32 REAL_64
COBOL FLOAT-BINARY-7 FLOAT-BINARY-34 FLOAT-SHORT, FLOAT-LONG,FLOAT-EXTENDED
Matematyka Nie dotyczy Nie dotyczy Real

^ A Testandardowestałereal shortsireal lengthsmogą być wykorzystane do określenia, ile „short«S»long«s może być użytecznie prefiksem do»short real” i „long real”. Faktycznie wielkość „short real”, „real” i „long real” jest dostępny jako stałeshort max real,max realalong max realitd. Przy stałychshort small real,small realilong small realdostępny dla każdego rodzaju użytkownikaepsilon maszynowy.
^b Deklaracje pojedynczej precyzji często nie są honorowane
^c Wartość "n" jest dostarczana przez funkcjęSELECTED_REAL_KINDwewnętrzną.
^d Opcja czasu działaniaALGOL 68G--precision "number"może ustawić precyzję dlalong long reals na wymaganą „liczbę” cyfr znaczących. Dookreślenia rzeczywistej dokładności można użyćstałychstandardowychlong long real widthi 'long long max real.
^e Te typy zmiennoprzecinkowe IEEE zostaną wprowadzone w następnym standardzie COBOL.
^f Taki sam rozmiar jak 'double' w wielu implementacjach.
^g Swift obsługuje 80-bitowytyp zmiennoprzecinkowy orozszerzonej precyzji, odpowiedniklong doublew językach C.

Liczby zespolone

Liczba całkowita Pojedyncza precyzja Podwójna precyzja Połowa i poczwórna precyzja itp.
Ada Nie dotyczy Complex Complex Complex
ALGOL 68 Nie dotyczy compl long compl itp. short complitd. i long long complitd.
C (C99) Nie dotyczy float complex double complex Nie dotyczy
C++ (STL) Nie dotyczy std::complex<float> std::complex<double>
DO# Nie dotyczy Nie dotyczy System.Numerics.Complex
(.NET 4.0)
Jawa Nie dotyczy Nie dotyczy Nie dotyczy
Udać się Nie dotyczy complex64 complex128
re Nie dotyczy cfloat cdouble
Cel C Nie dotyczy Nie dotyczy Nie dotyczy
Wspólne seplenienie (złożona liczba całkowita) (złożony jednopływak) (złożona podwójna pływak) złożony
Schemat Nie dotyczy
Pascal Nie dotyczy Nie dotyczy
Visual Basic Nie dotyczy Nie dotyczy
Visual Basic .NET Nie dotyczy Nie dotyczy System.Numerics.Complex
(.NET 4.0)
Perl Math::Complex
Raku complex64 complex128 Complex
Pyton complex Nie dotyczy
JavaScript Nie dotyczy Nie dotyczy
Gwara Nie dotyczy Nie dotyczy
Fortran COMPLEX(KIND = n)
Rubin Complex Nie dotyczy Complex
Scala Nie dotyczy Nie dotyczy Nie dotyczy
Nasiona7 Nie dotyczy Nie dotyczy complex
Pogawędka Complex Complex Complex
Windows PowerShell Nie dotyczy Nie dotyczy
OCaml Nie dotyczy Nie dotyczy Complex.t
FA# System.Numerics.Complex
(.NET 4.0)
Standardowy ML Nie dotyczy Nie dotyczy Nie dotyczy
Haskella (GHC) Nie dotyczy Complex.Complex Float Complex.Complex Double
Eiffla Nie dotyczy Nie dotyczy Nie dotyczy
COBOL Nie dotyczy Nie dotyczy Nie dotyczy
Matematyka Complex Nie dotyczy Nie dotyczy Complex

^a Wartość "n" jest dostarczana przez funkcjęSELECTED_REAL_KINDwewnętrzną.

^b Typ ogólny, który można utworzyć za pomocą dowolnego bazowego typu zmiennoprzecinkowego.

Inne typy zmiennych

Tekst Boole'a Wyliczenie Obiekt / Uniwersalny
Postać Strunowy
Ada Character String, Bounded_String,Unbounded_String Boolean ( item1, item2, ... ) tagged null record
ALGOL 68 char string, bytes bool, bits N/A — zdefiniowany przez użytkownika Nie dotyczy
C (C99) char, wchar_t Nie dotyczy bool enum «name» { item1, item2, ... }; void *
C++ (STL) «std::»string
Cel C unichar NSString * BOOL id
DO# char string bool enum name { item1« = value», item2« = value», ... } obiekt
Jawa String boolean enum name { item1, item2, ... } Object
Udać się byte, rune string bool
const (
  item1 = iota
  item2
  ...
)
interface{}
Rdza char String bool
enum name { item1« = value», item2« = value», ... }
std::any::Any
Szybki Character String Bool enum name { case item1, item2, ... } Any
re char string bool enum name { item1, item2, ... } std.variant.Variant
Wspólne seplenienie character string boolean (member item1 item2 ...) t
Schemat
ISLISP
Paskal (ISO) char Nie dotyczy boolean ( item1, item2, ... ) Nie dotyczy
Pascal obiektu (Delphi) string variant
Visual Basic Nie dotyczy String Boolean
Enum name
  item1 «= value»
  item2 «= value»
  ...
End Enum
Variant
Visual Basic .NET Char Object
Xojo Nie dotyczy Object lub Variant
Pyton Nie dotyczy str bool
from enum import Enum
class Name(Enum):
  item1 = value
  item2 = value
  ...
object
JavaScript Nie dotyczy String Boolean Object
Gwara
Fortran CHARACTER(LEN = *) CHARACTER(LEN = :), allocatable LOGICAL(KIND = n) CLASS(*)
PHP Nie dotyczy string bool (pominięto deklarację typu)
Perl Nie dotyczy UNIVERSAL
Raku Char Str Bool enum name<item1 item2 ...>
enum name <<:item1(value) :item2(value) ..>>
Mu
Rubin Nie dotyczy String Object Object
Scala Char String Boolean
object name extends Enumeration {
  val item1, item2, ... = Value
}
Any
Nasiona7 char string boolean
const type: name is new enum
  item1,
  item2,
  ...
end enum;
Windows PowerShell
OCaml char string bool Nie dotyczy Nie dotyczy
FA# type name = item1 = value |item2 = value | ... obj
Standardowy ML Nie dotyczy Nie dotyczy
Haskella (GHC) Char String Bool Nie dotyczy Nie dotyczy
Eiffla CHARACTER STRING BOOLEAN Nie dotyczy ANY
COBOL PIC X PIC X(string length) lub PIC X«X...» PIC 1«(number of digits lub PIC 1«1...» Nie dotyczy OBJECT REFERENCE
Matematyka Nie dotyczy String Nie dotyczy

^a konkretnie, ciągi o dowolnej długości i zarządzane automatycznie.
^b Ten język reprezentuje wartość logiczną jako liczbę całkowitą, gdzie fałsz jest reprezentowana jako wartość zero, a prawda przez wartość niezerową.
^c Wszystkie wartości mają wartość prawda lub fałsz. Wszystko wTrueClasswartościuje się jako prawdziwe, a wszystko wFalseClasswartościuje się w fałsz.
^d Ten język nie ma oddzielnego typu znaków. Znaki są reprezentowane jako ciągi o długości 1.
^e Wyliczenia w tym języku są typami algebraicznymi z tylko konstruktorami nullar
^f Wartość "n" jest dostarczana przez funkcjęSELECTED_INT_KINDwewnętrzną.

Typy pochodne

Szyk

tablica o ustalonym rozmiarze dynamiczna tablica rozmiarów
tablica jednowymiarowa tablica wielowymiarowa tablica jednowymiarowa tablica wielowymiarowa
Ada array (<first> .. <last>) of <type>
lub
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»
lub po prostu:
[size]«modename»
[first1:last1, first2:last2]«modename»
lub itp.
[first1:last1][first2:last2]«modename»
flex[first:last]«modename»
lub po prostu:
flex[size]«modename»
flex[first1:last1, first2:last2]«modename»
lub
flex[first1:last1]flex[first2:last2]«modename» etc.
C (C99) type name[size] type name[size1][size2] type *name
lub w obrębie bloku:
int n = ...; type name[n]
C++ (STL) «std::»array<type, size>(C++11) «std::»vector<type>
DO# type[] type[,,...] System.Collections.ArrayList
or
System.Collections.Generic.List<type>
Jawa type[] type[][]... ArrayList or ArrayList<type>
re type[size] type[size1][size2] type[]
Udać się [size]type [size1][size2]...type []type [][]type
Rdza [type; size] [[type; size1]; size2] Vec<type> Vec<Vec<type>>
Szybki [type] lub Array<type> [[type]] lub Array<Array<type>>
Cel C NSArray NSMutableArray
JavaScript Nie dotyczy Nie dotyczy Array
Wspólne seplenienie (simple-array type (dimension)) (simple-array type (dimension1 dimension2)) (array type (dimension)) (array type (dimension1 dimension2))
Schemat
ISLISP
Pascal array[first..last] of type array[first1..last1] of array[first2..last2] ... of type

lub
array[first1..last1, first2..last2, ...] of type

Nie dotyczy Nie dotyczy
Pascal obiektu (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)
Pyton list
Gwara 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
Rubin x = Array.new(size1){ Array.new(size2) } Array
Scala Array[type] Array[...[Array[type]]...] ArrayBuffer[type]
Nasiona7 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
Pogawędka Array OrderedCollection
Windows PowerShell type[] type[,,...]
OCaml type array type array ... array
FA# type [] or type array type [,,...] System.Collections.ArrayList
or
System.Collections.Generic.List<type>
Standardowy ML type vector or type array
Haskella (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. Nie dotyczy

^a W większości wyrażeń (z wyjątkiemoperatorówsizeofi&) wartości typów tablicowych w C są automatycznie konwertowane na wskaźnik pierwszego argumentu. ZobaczC syntax#Arrays,aby uzyskać więcej informacji na temat składni i operacji na wskaźnikach.
^b Podobny do Cdziała w Javie, jednakjest preferowaną formą deklaracji tablicy. ^c Podzakresy służą do definiowania granic tablicy. ^d Tablice JavaScript są specjalnym rodzajem obiektu. ^ e klauzula COBOL nie tworzy „prawdziwy” zmiennej długości tablicy, ale zawsze będzie przeznaczyć maksymalnego rozmiaru tablicy. type x[]type[] x


DEPENDING ON

Inne rodzaje

Proste typy kompozytowe Algebraiczne typy danych Związki
Dokumentacja Wyrażenie krotki
Ada
type name is «abstract» «tagged» «limited» [record
  field1 : type;
  field2 : type;
  ...
end record | null record]
Nie dotyczy Dowolna kombinacja rekordów, unii i wyliczeń (a także odwołań do nich, umożliwiających typy rekurencyjne).
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», ...); Wymagane typy i operatory mogą być zdefiniowane przez użytkownika union (modename, ...);
C (C99) struct «name» {type name;...}; Nie dotyczy Nie dotyczy union {type name;...};
Cel C
C++ struct «name» {type name;...}; «std::»tuple<type1..typen>
DO# struct name {type name;...} (val1, val2, ... ) Nie dotyczy
Jawa Nie dotyczy
JavaScript Nie dotyczy
re struct name {type name;...} std.variant.Algebraic!(type,...) union {type name;...}
Udać się
struct {
  «name» type
  ...
}
Rdza struct name {name: type, ...} (val1, val2, ... ) enum name { Foo(types), ...} union name {name: type, ...}
Szybki
struct name {
  var name «: type»
  ...
}
(«name1:» val1, «name2:» val2, «name3:» val3, ... ) enum name { case Foo«(types)» case Bar «(types)» ... }
Wspólne seplenienie (defstruct name slot-name (slot-name initial-value) (slot-name initial-value :type type) ...) (cons val1 val2)
Schemat Nie dotyczy
ISLISP
Pascal
record
  name: type;
  ...
end
Nie dotyczy Nie dotyczy
record
  case type of
  value: (types);
  ...
end
Visual Basic
Visual Basic .NET
Structure name
  Dim name As type
  ...
End Structure
(val1, val2, ... )
Pyton Nie dotyczy «(»val1, val2, val3, ... «)» Nie dotyczy
Gwara struct {name [=value], ...}
Fortran
TYPE name
  type :: name
  ...
END TYPE
PHP Nie dotyczy
Perl Nie dotyczy Nie dotyczy
Raku Nie dotyczy
Rubin 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
  ...

lub

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

lub połączenie klas przypadków i obiektów przypadków

Windows PowerShell
OCaml type name = {«mutable» name : type;...} «(»val1, val2, val3, ... «)» type name = Foo «of type» | Bar «of type» | ... Nie dotyczy
FA#
Standardowy ML type name = {name : type,...} (val1, val2, val3, ... ) datatype name = Foo «of type» | Bar «of type» | ...
Haskell data Name = Constr {name :: type,...} data Name = Foo «types» | Bar «types» | ...
COBOL
level-number name type clauses.
  level-number+n name type clauses.
  ...
Nie dotyczy Nie dotyczy name REDEFINES variable type.

^a Obsługiwane są tylko klasy.
^b struct w C++ są w rzeczywistości klasami, ale mają domyślną widoczność publiczną irównieżobiektamiPOD. C++11 rozszerzył to dalej, aby klasy działały identycznie jak obiekty POD w wielu innych przypadkach.
^c tylko para
^d Chociaż Perl nie ma rekordów, ponieważ system typów Perla pozwala na umieszczanie różnych typów danych w tablicy, „hasze” (tablice asocjacyjne), które nie mają indeksu zmiennej, byłyby faktycznie takie same jak rekordy .
^e Wyliczenia w tym języku są typami algebraicznymi z tylko konstruktorami nullary

Deklaracje zmiennych i stałych

zmienna stały wpisz synonim
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;
Cel C
C++ const type name = value;
DO# 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;
re type name« = initial_value»; or
auto name = value;
const type name = value; or
immutable type name = value;
alias type synonym;
Jawa type name« = initial_value»; final type name = value; Nie dotyczy
JavaScript var name« = initial_value»;lub (od ECMAScript 2015)
let name« = initial_value»;
const name = value;(od ECMAScript 2015)
Udać się var name type« = initial_value» or
name := initial_value
const name «type» = value type synonym type
Rdza 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;
Szybki var name« : type»« = initial_value» let name «: type» = value typealias synonym = type
Wspólne seplenienie (defparameter name initial-value) or
(defvar name initial-value)
(defconstant name value) (deftype synonym () 'type)
Schemat (define name initial_value)
ISLISP (defglobal name initial_value) or
(defdynamic name initial_value)
(defconstant name value) Nie dotyczy
Pascal name: type« = initial_value» name = value synonym = type
Visual Basic Dim name «As type» Zobacz notatki po lewej.

Stałe używają tej samej składni i:

  • użyj ConstzamiastDim
  • mieć ograniczenie tylko do niektórych typów prymitywnych

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

Visual Basic .NET Składnia deklaracji zmiennych VB.NET jest zaskakująco trudna do precyzyjnego opisania.

Biorąc pod uwagę, że istnieją sufiksy identyfikatora ("modyfikatory"):

  • type_character, dostępny jako alternatywa dla Asklauzuli dla niektórych typów danych pierwotnych;
  • nullable_specifier; i
  • array_specifier;

i to

  • a modified_identifierma formę identifier«type_character»«nullable_specifier»«array_specifier»;
  • a modified_identifier_listto rozdzielona przecinkami lista dwóch lub więcej wystąpień modified_identifier; i
  • a declarator_listto rozdzielona przecinkami lista deklaratorów, która może mieć postać
    • identifier As object_creation_expression (deklarator inicjatora obiektów) ,
    • modified_identifier« As non_array_type«array_rank_specifier»»« = initial_value» (pojedynczy deklarator) , lub
    • modified_identifier_list« As «non_array_type««array_rank_specifier»» (wielokrotny deklarator);

ważne deklaracje mają formę

Dim declarator_list,

gdzie, do celów analizy semantycznej, przekonwertować the declarator_listna listę tylko pojedynczych deklaratorów:

Te Asklauzule każdego stwardnienie declarator jest rozłożone na jegomodified_identifier_list
As New type...Każdego obiektu inicjatora declarator jest zastąpionyAs type = New type...

i dla których, dla każdego identifier,

  • a type_characteri Asklauzula nie pojawiają się oba;
  • jeśli występuje Asklauzula,
    • an array_rank_specifiernie występuje zarówno jako modyfikacja identyfikatora, jak i typu Asklauzuli;
  • a unmodified_typemożna określić, stosując zasadę, że
    • jeśli występuje klauzula type_characterlub As,
      • unmodified_type czy to jest określone przez taką konstrukcję,
    • i że inaczej,
      • albo Option Infermusi być włączony i identifiermusi mieć inicjator, w tym przypadku unmodified_typejest to inicjator, lub
      • Option Strictmusi być wyłączony, w takim przypadku unmodified_typejest Object;
  • jego final_typejest jego unmodified_typedołączany na początku przed jego modyfikatory;
  • jej final_typejest prawidłowy typ; i
  • jeśli initial_valuewystępuje,
    • albo Option Strictjest włączony i initial_valuema konwersję rozszerzającą do final_type, lub
    • Option Strictjest wyłączona i initial_valuema zawężoną konwersję do final_type.

Jeśli Option Explicitjest wyłączone, zmienne nie wymagają jawnej deklaracji; są deklarowane niejawnie, gdy są używane:

name = initial_value

Imports synonym = type
Xojo Dim name «As type»« = initial_value» Nie dotyczy
Pyton name = initial_value Nie dotyczy synonym = type
CoffeeScript Nie dotyczy
Gwara name = initial_value; typedef struct {...} typename
Fortran Wpisz imię type, PARAMETER :: name = value
PHP $name = initial_value; define("name", value);
const name = value (5.3+)
Nie dotyczy
Perl «my» $name« = initial_value»; use constant name => value;
Raku «my «type»» $name« = initial_value»; «my «type»» constant name = value; ::synonym ::= type
Rubin 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 Nie dotyczy Nie dotyczy
Bash powłoki B name=initial_value Nie dotyczy Nie dotyczy
OCaml let name« : type ref» = ref value let name «: type» = value type synonym = type
FA# let mutable name« : type» = value
Standardowy ML val name« : type ref» = ref value val name «: type» = value
Haskell «name::type;» name = value type Synonym = type
Naprzód VARIABLE name(w niektórych systemach użyj zamiast) 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.
Matematyka name=initial_value Nie dotyczy Nie dotyczy

^a Pascal ma bloki deklaracji. Zobaczfunkcje.
^b Typy to zwykłe obiekty, więc możesz je po prostu przypisać.
^c W Perlu słowo kluczowe "my" obejmuje zmienną w bloku.
^d Technicznie rzecz biorąc, nie oznacza to, żenazwajest zmienną zmienną — w ML wszystkie nazwy można powiązać tylko raz; raczej deklarujename,aby wskazywać na strukturę danych „referencyjną”, która jest prostą komórką zmienną. Strukturę danych można następnie odczytywać i zapisywać przy użyciu odpowiedniooperatorów!i:=.
^e Jeśli nie podano wartości początkowej, automatycznie przypisywana jest nieprawidłowa wartość (co wyzwoli wyjątek czasu wykonania, jeśli zostanie użyta przed przypisaniem prawidłowej wartości). Chociaż to zachowanie można stłumić, jest to zalecane ze względu na przewidywalność. Jeśli nie można znaleźć nieprawidłowej wartości dla typu (na przykład w przypadku typu liczby całkowitej bez ograniczeń), zamiast tego wybierana jest prawidłowa, ale przewidywalna wartość.
^f W Rust, jeśli nie podano wartości początkowejzmiennejletlublet muti nigdy nie zostanie ona później przypisana, pojawi sięostrzeżenie „nieużywana zmienna”. Jeśli nie podano wartości dlaconstlubstaticlubstatic mutzmiennej, wystąpił błąd. Wprzypadkuconstzmiennych, którenie są pisane wielkimi literami, występuje błąd„globalnenie pisane wielkimi literami”. Po zdefiniowaniustatic mutzmienna może być przypisana tylko wunsafebloku lub funkcji.

Kontrola przepływu

Oświadczenia warunkowe

gdyby inaczej, jeśli wybierz przypadek wyrażenie warunkowe
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
 )

lub

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

jeśli warunek 1 to

  statements
elsif condition2 then
  statements
...
«else
  statements»
end if
case expression of
  when set1 : statements
  ...
  «otherwise: statements»
end case
Moduł-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
(formularz skrócony)
( 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) oraz:
  • Cel C
  • C++ (STL)
  • re
  • Jawa
  • JavaScript
  • PHP
if (condition) instructions
«else instructions»

instructions może być pojedynczą instrukcją lub blokiem w postaci: { statements }

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

lub

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

instructions może być pojedynczą instrukcją lub blokiem w postaci: { 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»
}

Wszystkie niepuste przypadki muszą kończyć się stwierdzeniem breaklub goto case(to znaczy, że nie mogą przejść do następnego przypadku). defaultSprawa nie jest wymagane, aby przyjść ostatni.

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 }»}
Udać się
if condition {instructions}
«else {instructions}»
if condition {instructions}
else if condition {instructions}
...
«else {instructions}»

lub

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

lub

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

lub

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}»

lub

unless notcondition {instructions}
if condition {instructions} 
elsif condition {instructions} 
...
«else {instructions}
given variable {
  when case1 { instructions }
  ...
  «default { instructions }»
}
condition ?? valueIfTrue !! valueIfFalse
Rubin
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
Pogawędka
condition ifTrue:
  trueBlock
«ifFalse:
  falseBlock»
end
condition ifTrue: trueBlock ifFalse: falseBlock
Wspólne seplenienie
(when condition
  instructions)

lub

(unless condition
  instructions)

lub

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

lub

(cond (test1 value1) (test2 value2) ...))
Schemat
(when condition instructions)

lub

(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

Jednowierszowy, gdy instructionssą : instruction1 : instruction2 : ...

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

Pojedyncza linia:

Zobacz notatkę o językach podobnych do C; Elseklauzula o pojedynczej linii Ifrachunku może zawierać inny pojedynczej linii Ifoświadczenie.

Select« Case» variable
  Case case_pattern1
    instructions
  ...
  «Case Else
    instructions»
End Select
IIf(condition, valueIfTrue, valueIfFalse)
Visual Basic .NET If(condition, valueIfTrue, valueIfFalse)
Xojo
Pyton
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
Gwara 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
Naprzód 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
FA# Tryb lekkiej składni:

W jednej linii lub z wcięciem, jak pokazano poniżej:

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

Tryb pełnej składni:

Tak samo jak w przypadku standardowej ML (poniżej).

Tryb lekkiej składni:

W jednej linii lub z wcięciem, jak pokazano poniżej:

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

Tryb pełnej składni:

Tak samo jak w przypadku standardowej ML (poniżej).

Standardowy ML
if condition then «(»instructions «)»
else «(» instructions «)»
if condition then «(»instructions «)»
else if condition then «(» instructions «)»
...
else «(» instructions «)»
case value of
  pattern1 => expression
  | pattern2 => expression
  ...
  «| _ => expression»
Haskella (GHC)
if condition then expression else expression

lub

when condition (do instructions)

lub

unless notcondition (do instructions)
result | condition = expression
  | condition = expression
  | otherwise = expression
case value of {
  pattern1 -> expression;
  pattern2 -> expression;
  ...
  «_ -> expression»
}
Bash powłoki B
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»

lub

if condition
  expression
«else
  expression»

lub

expression if condition

lub

unless condition
  expression
«else
  expression»

lub

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

lub

if condition
  expression
else if condition
  expression
«else
  expression»

lub

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

lub

switch expression
  when condition
    expression
  «else
    expression»
Wszystkie warunki są wyrażeniami.
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
Rdza
if condition {
  expression 
}« else {
  expression 
}»
if condition {
  expression 
} else if condition {
  expression 
}« else {
  expression 
}»
match variable {
   pattern1 => expression,
   pattern2 => expression,
   pattern3 => expression,
  «_ => expression»
}

Wszystkie warunki są wyrażeniami

gdyby inaczej, jeśli wybierz przypadek wyrażenie warunkowe

^a Pojedyncza instrukcja może być napisana w tym samym wierszu po dwukropku. Wiele instrukcji jest zgrupowanych wbloku,który zaczyna się od nowej linii (wymagane jest wcięcie). Składnia wyrażeń warunkowych nie jest zgodna z tą zasadą.
^b To jestdopasowanie do wzorcai jest podobne do wybranego przypadku, ale nie takie samo. Jest zwykle używany do dekonstrukcjialgebraicznych typów danych.
^c W językach z rodziny Pascal średnik nie jest częścią stwierdzenia. Jest separatorem między instrukcjami, a nie terminatorem.
^d END-IF może być użyte zamiast kropki na końcu.
^e W Rust przecinek,na końcu dopasowania może zostać pominięty po ostatnim dopasowanym ramieniu lub po dowolnym dopasowanym ramieniu, w którym wyrażenie jest blokiem (kończy się prawdopodobnie pustymi pasującymi nawiasami{}).

Instrukcje pętli

podczas zrób chwilę dla i = od pierwszego do ostatniego dla każdego
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

lub

(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 może być pojedynczą instrukcją lub blokiem w postaci: { statements }
while (condition) instructions
do instructions while (condition);
for («type» i = first; i <= last; i++) instructions
Nie dotyczy
Cel C
for (type item in set) instructions
C++ (STL)
«std::»for_each(start, end, function)

Od C++11 :

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

Od EcmaScript 2015:

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

lub

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

lub

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

1.x:

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

lub

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

lub

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

lub

until (notcondition) { instructions }

wykonaj { instrukcje } while ( warunek ) lub

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

lub

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

lub

until notcondition { instructions }
repeat { instructions } while condition

lub

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

lub

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

lub

until notcondition
  instructions
end
begin
  instructions
end while condition

lub

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

lub

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

lub

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

lub

set.each { |item| instructions }
Bash powłoki B
while condition ;do
  instructions
done

lub

until notcondition ;do
  instructions
done
Nie dotyczy
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 }

lub

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

lub

set foreach (item => { instructions })
Pogawędka
conditionBlock whileTrue:
  loopBlock
loopBlock doWhile:
  conditionBlock
first to: last do:
  loopBlock
collection do:
  loopBlock
Wspólne seplenienie
(loop
  while condition
  do
  instructions)

lub

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

lub

(dotimes (i N)
  instructions)

lub

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

lub

(loop
  for item across vector
  do
  instructions)

lub

(dolist (item list)
  instructions)

lub

(mapc function list)

lub

(map 'type function sequence)
Schemat
(do () (notcondition) instructions)

lub

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

lub

(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

lub

Do Until notcondition
  instructions
Loop

lub

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

lub

Do
  instructions
Loop Until notcondition
i musi być zgłoszone wcześniej.
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

lub

Do
  instructions
Loop Until notcondition
Pyton
while condition :
Tab ↹ instructions
«else:
Tab ↹ instructions»
Nie dotyczy 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»
Gwara
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
Nie dotyczy
Naprzód
BEGIN « instructions » condition WHILE instructions REPEAT
BEGIN  instructions condition UNTIL
limit start DO instructions LOOP
Nie dotyczy
OCaml
while condition do instructions done
Nie dotyczy
for i = first to last do instructions done
Array.iter (fun item -> instructions) array

lub

List.iter (fun item -> instructions) list
FA#
while condition do
Tab ↹ instructions
Nie dotyczy
for i = first to last do
Tab ↹ instructions
for item in set do
Tab ↹ instructions

lub

Seq.iter (fun item -> instructions) set
Standardowy ML
while condition do ( instructions )
Nie dotyczy
Array.app (fn item => instructions) array

lub

app (fn item => instructions) list
Haskella (GHC) Nie dotyczy
Control.Monad.forM_ [first..last] (\i -> do instructions)
Control.Monad.forM_ list (\item -> do instructions)
Eiffla
from
  setup
until
  condition
loop
  instructions
end
CoffeeScript
while condition
  expression

lub

expression while condition

lub

while condition then expression

lub

until condition
  expression

lub

expression until condition

lub

until expression then condition
Nie dotyczy
for i in [first..last]
  expression

lub

for i in [first..last] then expression

lub

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

lub

for item in set then expression

lub

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

lub

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

lub

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

lub

PERFORM VARYING i FROM first BY increment UNTIL i > last
  expression
END-PERFORM
Nie dotyczy
Rdza
while condition {
  expression
}
loop {
  expression
  if condition {
      break;
  }
}
for i in first..last+1 {
  expression
}

lub

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

lub

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

^a "stepn" służy do zmiany interwału pętli. Jeślisteppominięto„”, interwał pętli wynosi 1.

^b To implementujekwantyfikator uniwersalny(„dla wszystkich” lub „∀”), a takżekwantyfikator egzystencjalny(„istnieje” lub „∃”).

^c THRU można użyć zamiastTHROUGH.

^d można użyć zamiast. «IS» GREATER «THAN»>

^e Typ wyrażenia set musi implementować cechęstd::iter::IntoIterator.

Wyjątki

rzucać treser twierdzenie
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 } ...
DO# try { instructions } catch «(exception« name»)» { instructions } ... «finally { instructions }» System.Diagnostics.Debug.Assert(condition);lub

System.Diagnostics.Trace.Assert(condition);

Jawa try { instructions } catch (exception) { instructions } ... «finally { instructions }» assert condition «: description»;
JavaScript try { instructions } catch (exception) { instructions } «finally { instructions }» ?
re try { instructions } catch (exception) { instructions } ... «finally { instructions }» assert(condition);
PHP try { instructions } catch (exception) { instructions } ... «finally { instructions }» assert(condition);
Gwara try { instructions } catch «exception» { instructions } ... «finally { instructions }» ?
Windows PowerShell trap «[exception]» { instructions } ... instructions or try { instructions } catch «[exception]» { instructions } ... «finally { instructions }» [Debug]::Assert(condition)
Cel C @throw exception; @try { instructions } @catch (exception) { instructions } ... «@finally { instructions }» NSAssert(condition, description);
Szybki 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 } ...}} ?
Rubin raise exception begin
instructions
rescue exception
instructions
...
«else
instructions»
«ensure
instructions»
end
Pogawędka exception raise instructionBlock on: exception do: handlerBlock assert: conditionBlock
Wspólne seplenienie (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)
Schemat (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 exceptionlub

Error errorcode

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

System.Diagnostics.Trace.Assert(condition)

Xojo Raise exception Try
instructions
Catch «exception»
instructions
...
«Finally
instructions»
End Try
Nie dotyczy
Pyton raise exception try:
Tab ↹ instructions
except «exception»:
Tab ↹ instructions
...
«else:
Tab ↹ instructions»
«finally:
Tab ↹ instructions»
assert condition
Fortran Nie dotyczy
Naprzód code THROW xt CATCH ( code or 0 ) Nie dotyczy
OCaml raise exception try expression with pattern -> expression ... assert condition
FA# try expression with pattern -> expression ...
or
try expression finally expression
Standardowy ML raise exception «arg» expression handle pattern => expression ...
Haskella (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».
Nie dotyczy
Rdza Nie assert!(condition)

^ a Common Lisp pozwalawith-simple-restart,restart-caseirestart-bindzdefiniować restartów do stosowaniainvoke-restart. Nieobsłużone warunki mogą spowodować, że implementacja wyświetli użytkownikowi menu restartów przed rozwinięciem stosu.

^b Nieprzechwycone wyjątki są propagowane do najbardziej wewnętrznego, dynamicznie otaczającego wykonania. Wyjątki nie są propagowane między zadaniami (chyba że te zadania są obecnie synchronizowane podczas spotkania).


Inne instrukcje przepływu sterowania control

blok wyjścia (przerwa) kontyntynuj etykieta oddział ( przejdź do ) zwracać wartość z generatora
Ada exit «loop_name» «when condition» Nie dotyczy label: goto label Nie dotyczy
ALGOL 68 value exit; ... do statements; skip exit; label: statements od label: ... go to label; ...
goto label; ...
label; ...
yield(value)

( oddzwonienie )

APL :Leave :Continue label: label
or
:GoTo label
Nie dotyczy
C (C99) break; continue; label: goto label; Nie dotyczy
Cel C
C++ (STL)
re
DO# yield return value;
Jawa break «label»; continue «label»; Nie dotyczy
JavaScript yield value«;»
PHP break «levels»; continue «levels»; goto label; yield «key =>» value;
Perl last «label»; next «label»;
Raku
Udać się break «label» continue «label» goto label
Szybki break «label» continue «label» Nie dotyczy
Bash powłoki B break «levels» continue «levels» Nie dotyczy Nie dotyczy Nie dotyczy
Wspólne seplenienie (return) or
(return-from block) or
(loop-finish)
(tagbody tag
...
tag
...)
(go tag)
Schemat
ISLISP (return-from block) (tagbody tag
...
tag
...)
(go tag)
Paskal (ISO) Nie dotyczy label: goto label; Nie dotyczy
Pascal (ZKP) break; continue;
Visual Basic Exit blockAlternatywnie, dla metod,

Return

Nie dotyczy label: GoTo label
Xojo Continue block
Visual Basic .NET Yield value
Pyton break continue Nie dotyczy yield value
RPG IV LEAVE; ITER;
Gwara break; continue;
Fortran EXIT CYCLE label GOTO label Nie dotyczy
Rubin break next
Windows PowerShell break «label» continue
OCaml Nie dotyczy
FA#
Standardowy ML
Haskella (GHC)
COBOL EXIT PERFORM or EXIT PARAGRAPH or EXIT SECTION or EXIT. EXIT PERFORM CYCLE label «SECTION». GO TO label Nie dotyczy

^a Pascal ma bloki deklaracji. Zobaczfunkcje. Etykieta
^b musi być liczbą z zakresu od 1 do 99999.

Funkcje

Zobacz odbicie dla wywoływania i deklarowania funkcji przez ciągi.

wywoływanie funkcji funkcja podstawowa/unieważniona funkcja zwrotu wartości value wymagana główna funkcja
Ada foo «(parameters)» procedure foo «(parameters)» is begin statements end foo function foo «(parameters)» return type is begin statements end foo Nie dotyczy
ALGOL 68 foo«(parameters)»; proc foo = «(parameters)» void: ( instructions ); proc foo = «(parameters)» rettype: ( instructions ...; retvalue ); Nie dotyczy
APL «parameters» foo parameters foo{ statements } foo{ statements } Nie dotyczy
C (C99) foo(«parameters») void foo(«parameters») { instructions } type foo(«parameters») { instructions ... return value; } «global declarations»
int main(«int argc, char *argv[]») {
instructions
}
Cel C
C++ (STL)
Jawa public static void main(String[] args) { instructions } or
public static void main(String... args) { instructions }
re int main(«char[][] args») { instructions} or
int main(«string[] args») { instructions} or
void main(«char[][] args») { instructions} or
void main(«string[] args») { instructions}
DO# Tak samo jak powyżej; alternatywnie, jeśli tylko jedno stwierdzenie:

void foo(«parameters») => statement;

Tak samo jak powyżej; alternatywnie, jeśli jest wystarczająco proste, aby być wyrażeniem:

void foo(«parameters») => expression;

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

Może zamiast tego wrócić int.

(zaczynając od C# 7.1:) Może zwrócić Tasklub Task<int>, a jeśli tak, może być 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; } Nie dotyczy
Udać się func foo(«parameters») { instructions } func foo(«parameters») type { instructions ... return value } func main() { instructions }
Szybki func foo(«parameters») { instructions } func foo(«parameters») -> type { instructions ... return value } Nie dotyczy
Wspólne seplenienie (foo «parameters») (defun foo («parameters»)
instructions)
or
(setf (symbol-function 'symbol)
function)
(defun foo («parameters»)
...
value)
Nie dotyczy
Schemat (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 Tak samo jak powyżej; alternatywnie: Function Foo«(parameters)»« As type»
instructions
Return value
End Function


AsKlauzula nie jest wymagane, jeśli Option Strictjest wyłączony. Zamiast Asklauzuli można użyć znaku typu .

Jeśli formant kończy działanie funkcji bez jawnie określonej wartości zwracanej, funkcja zwraca wartość domyślną dla typu zwracanego.

Sub Main(««ByVal »args() As String»)
instructions
End Sub
lub Function Main(««ByVal »args() As String») As Integer
instructions
End Function
Xojo
Pyton foo(«parameters») def foo(«parameters»):
Tab ↹ instructions
def foo(«parameters»):
Tab ↹ instructions
Tab ↹ return value
Nie dotyczy
Gwara 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
Naprzód «parameters» FOO : FOO « stack effect comment: ( before -- ) »
instructions
;
: FOO « stack effect comment: ( before -- after ) »
instructions
;
Nie dotyczy
PHP foo(«parameters») function foo(«parameters») { instructions } function foo(«parameters») { instructions ... return value; } Nie dotyczy
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; }
Rubin foo«(parameters)» def foo«(parameters)»
instructions
end
def foo«(parameters)»
instructions
«return» value
end
Rdza 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 }
Nie dotyczy
Bash powłoki B foo «parameters»

function foo {
    instructions
}
lub
foo () {
    instructions
}

function foo {
    instructions
    return «exit_code»
}
lub
foo () {
    instructions
    return «exit_code»
}

  • parametry
    • $n( $ 1 , $ 2 , $ 3 , ...)
    • $@ (wszystkie parametry)
    • $# (liczba parametrów)
    • $0 (ta nazwa funkcji)
OCaml foo parameters let «rec» foo parameters = instructions let «rec» foo parameters = instructions... return_value
FA# [<EntryPoint>] let main args = instructions
Standardowy ML 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
Eiffla 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 Nie dotyczy
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.
Nie dotyczy
«FUNCTION» foo«(«parameters»)» Nie dotyczy

^a Pascal wymaga "forward;" doprzekazywania deklaracji.
^b Eiffel umożliwia określenie głównej klasy i funkcji aplikacji.
^c W Fortranie parametry funkcji/podprogramu nazywa się argumentami (ponieważPARAMETERjest słowem kluczowym języka); CALLHasło jest wymagane dla podprogramów.
^d Zamiast używać"foo", można użyć zmiennej łańcuchowej zawierającej tę samą wartość.

Wpisz konwersje

Gdzie string jest liczbą dziesiętną ze znakiem:

ciąg do liczby całkowitej ciąg do długiej liczby całkowitej ciąg do zmiennoprzecinkowego liczba całkowita na ciąg liczba zmiennoprzecinkowa na ciąg
Ada Integer'Value (string_expression) Long_Integer'Value (string_expression) Float'Value (string_expression) Integer'Image (integer_expression) Float'Image (float_expression)
ALGOL 68 z formatami ogólnymi, a następnie specyficznymi Z uprzednimi deklaracjami i stowarzyszeniem: 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));
lub
getf(proxy, ($dddd$, ivar));
getf(proxy, ($g$, livar));
lub
getf(proxy, ($8d$, livar));
getf(proxy, ($g$, rvar));
lub
getf(proxy, ($8d.4dE2d$, rvar));
putf(proxy, ($g$, ival));
lub
putf(proxy, ($4d$, ival));
putf(proxy, ($g(width, places, exp)$, rval));
lub
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);
Cel C integer = [string intValue]; long = [string longLongValue]; float = [string doubleValue]; string = [NSString stringWithFormat:@"%i", integer]; string = [NSString stringWithFormat:@"%f", float];
C++ (STL) «std::»istringstream(string) >> number; «std::»ostringstream o; o << number; string = 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);
DO# integer = int.Parse(string); long = long.Parse(string); float = float.Parse(string); double = double.Parse(string); string = number.ToString();
re 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)
Jawa 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}`
Udać się 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)
Rdza 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()
Wspólne seplenienie (setf integer (parse-integer string)) (setf float (read-from-string string)) (setf string (princ-to-string number))
Schemat (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

(można używać obu powyższych składni VB

i metody .NET pokazane po prawej)

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)
Pyton integer = int(string) long = long(string) float = float(string) string = str(number)
Gwara 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;
Rubin 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
Pogawędka 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
FA# let integer = int string let integer = int64 string let float = float string let string = string number
Standardowy ML val integer = Int.fromString string val float = Real.fromString string val string = Int.toString integer val string = Real.toString float
Haskella (GHC) number = read string string = show number
COBOL MOVE «FUNCTION» NUMVAL(string) TO number MOVE number TO numeric-edited

^a JavaScript używa tylko liczb zmiennoprzecinkowych, więc są pewne szczegóły techniczne.
^b Perl nie ma oddzielnych typów. Ciągi i cyfry są wymienne.
^c NUMVAL-C lubNUMVAL-Fmoże być użyty zamiastNUMVAL.
^ str::parse jest dostępny do konwersji dowolnego typu, który ma implementacjęstd::str::FromStrcechy. Obastr::parseiFromStr::from_strzwracają a,Resultktóre zawierają określony typ, jeśli nie ma błędu. Turbofish(::<_>) w sprawiestr::parsemogą być pominięte, jeśli typ można wywnioskować z kontekstu.

Standardowe we/wy strumienia

Czytaj od Napisz do
stdin stdout 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 );
Cel 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;
DO# 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);
re 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)
Jawa 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);
Udać się 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)
Szybki x = readLine() (2.x) print(x)(2.x) (1.x)
println(x)
Implementacja przeglądarki internetowej JavaScript
document.write(x)
Strony JavaScript
Active Server Server
Response.Write(x)
Host skryptów JavaScript w
systemie Windows
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)
Wspólne seplenienie (setf x (read-line)) (princ x) or
(format t format x)
(princ x *error-output*) or
(format *error-output* format x)
Schemat (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
Nie dotyczy
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)
Gwara 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
Naprzód buffer length ACCEPT ( # chars read )
KEY ( char )
buffer length TYPE
char EMIT
Nie dotyczy
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)
Rubin 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 ...
FA# let x = System.Console.ReadLine() printf format x ... or
printfn format x ...
eprintf format x ... or
eprintfn format x ...
Standardowy ML val str = TextIO.inputLIne TextIO.stdIn print str TextIO.output (TextIO.stdErr, str)
Haskella (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 dodatkowo jako "niesformatowane"procedurytransmisyjne:i. ^b iodczytaj niesformatowany tekst ze standardowego wejścia. Nie zaleca się używania pobiera. ^c inapisz niesformatowany tekst na standardowe wyjście. ^d zapisuje niesformatowany tekst na stderr ^e są zdefiniowane wmodule. 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

Odczytywanie argumentów wiersza poleceń

Wartości argumentów Argument się liczy Nazwa programu / Nazwa skryptu
Ada Argument (n) Argument_Count Command_Name
C (C99) argv[n] argc pierwszy argument
Cel C
C++
DO# args[n] args.Length Assembly.GetEntryAssembly().Location;
Jawa args.length
re pierwszy argument
Implementacja hosta skryptów systemu Windows w języku JavaScript
WScript.Arguments(n) WScript.Arguments.length WScript.ScriptName or WScript.ScriptFullName
Udać się os.Args[n] len(os.Args) pierwszy argument
Rdza 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()
Szybki Process.arguments[n] lub
Process.unsafeArgv[n]
Process.arguments.count lub
Process.argc
pierwszy argument
Wspólne seplenienie ? ? ?
Schemat (R 6 RS) (list-ref (command-line) n) (length (command-line)) pierwszy argument
ISLISP Nie dotyczy Nie dotyczy Nie dotyczy
Pascal ParamStr(n) ParamCount pierwszy argument
Visual Basic Command Nie dotyczy App.Path
Visual Basic .NET CmdArgs(n) CmdArgs.Length [Assembly].GetEntryAssembly().Location
Xojo System.CommandLine (parsowanie ciągu) Application.ExecutableFile.Name
Pyton sys.argv[n] len(sys.argv) pierwszy argument
Gwara __argv[n] __argc pierwszy 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 pierwszy argument
Bash powłoki B $n ($1, $2, $3, ...)
$@ (wszystkie argumenty)
$# $0
Perl $ARGV[n] scalar(@ARGV) $0
Raku @*ARGS[n] @*ARGS.elems $PROGRAM_NAME
Rubin ARGV[n] ARGV.size $0
Windows PowerShell $args[n] $args.Length $MyInvocation.MyCommand.Name
OCaml Sys.argv.(n) Array.length Sys.argv pierwszy argument
FA# args.[n] args.Length Assembly.GetEntryAssembly().Location
Standardowy ML List.nth (CommandLine.arguments (), n) length (CommandLine.arguments ()) CommandLine.name ()
Haskella (GHC) do { args <- System.getArgs; return length args !! n } do { args <- System.getArgs; return length args } System.getProgName
COBOL Nie dotyczy
  • ^ a rdza,std::env::argsistd::env::args_ositeratory powrotne,std::env::Argsistd::env::ArgsOsodpowiednio. Argskonwertuje każdy argument na aStringi wpada w panikę, jeśli osiągnie argument, którego nie można przekonwertować naUTF-8. ArgsOszwraca bezstratną reprezentację nieprzetworzonych ciągów z systemu operacyjnego (std::ffi::OsString), która może być niepoprawna w UTF-8.
  • ^b W Visual Basic argumenty wiersza polecenia nie są rozdzielane. Oddzielenie ich wymaga funkcji dzielenia.Split(string)
  • ^c Standard COBOL nie zapewnia dostępu do argumentów wiersza poleceń, ale powszechne rozszerzenia kompilatora umożliwiające dostęp do nich obejmują definiowanie parametrów dla programu głównego lub używanieACCEPTinstrukcji.

Wykonywanie poleceń

Polecenie powłoki Wykonaj program Zastąp bieżący program nowym wykonanym programem
Ada Nie jest częścią standardu językowego. Zwykle wykonywane przez pakiety dostarczone przez kompilator lub przez połączenie z C lub POSIX .
do system("command"); execl(path, args); or
execv(path, arglist);
C++
Cel C [NSTask launchedTaskWithLaunchPath:(NSString *)path arguments:(NSArray *)arguments];
DO# System.Diagnostics.Process.Start(path, argstring);
FA#
Udać się 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) Nie dotyczy
re std.process.system("command"); std.process.execv(path, arglist);
Jawa Runtime.exec(command); or
new ProcessBuilder(command).start();
Implementacja hosta skryptów systemu Windows w języku JavaScript
WScript.CreateObject ("WScript.Shell").Run(command «WindowStyle» «isWaitOnReturn»); WshShell.Exec(command)
Wspólne seplenienie (uiop:run-program command)
Schemat (system command)
ISLISP Nie dotyczy Nie dotyczy Nie dotyczy
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
Standardowy ML OS.Process.system command Unix.execute (path, args) Posix.Process.exec (path, args)
Haskella (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)
Rubin system(command) or
output = `command`
exec(path, args)
PHP system(command) or
$output = `command` or
exec(command) or
passthru(command)
Pyton os.system(command) or
subprocess.Popen(command)
subprocess.call(["program", "arg1", "arg2", …]) os.execv(path, args)
Gwara system(command)
Fortran CALL EXECUTE_COMMAND_LINE (COMMAND «, WAIT» «, EXITSTAT» «, CMDSTAT» «, CMDMSG»)
Windows PowerShell [Diagnostics.Process]::Start(command) «Invoke-Item »program arg1 arg2 …
Bash powłoki B output=`command` lub

output=$(command)

program arg1 arg2 …

^ Fortran 2008 lub nowszy.

Bibliografia