~~~~~~~~~~~~~~~~~~~~ Arc.Ask3.Ru ~~~~~~~~~~~~~~~~~~~~~ 
Номер скриншота №:
✰ 7E51D669B5BC1E225F14C2EF3F7DD33C__1717529700 ✰
Заголовок документа оригинал.:
✰ Comparison of programming languages (basic instructions) - Wikipedia ✰
Заголовок документа перевод.:
✰ Сравнение языков программирования (базовые инструкции) — Википедия ✰
Снимок документа находящегося по адресу (URL):
✰ https://en.wikipedia.org/wiki/Comparison_of_programming_languages_(basic_instructions) ✰
Адрес хранения снимка оригинал (URL):
✰ https://arc.ask3.ru/arc/aa/7e/3c/7e51d669b5bc1e225f14c2ef3f7dd33c.html ✰
Адрес хранения снимка перевод (URL):
✰ https://arc.ask3.ru/arc/aa/7e/3c/7e51d669b5bc1e225f14c2ef3f7dd33c__translat.html ✰
Дата и время сохранения документа:
✰ 21.06.2024 10:17:47 (GMT+3, MSK) ✰
Дата и время изменения документа (по данным источника):
✰ 4 June 2024, at 22:35 (UTC). ✰ 

~~~~~~~~~~~~~~~~~~~~~~ Ask3.Ru ~~~~~~~~~~~~~~~~~~~~~~ 
Сервисы Ask3.ru: 
 Архив документов (Снимки документов, в формате HTML, PDF, PNG - подписанные ЭЦП, доказывающие существование документа в момент подписи. Перевод сохраненных документов на русский язык.)https://arc.ask3.ruОтветы на вопросы (Сервис ответов на вопросы, в основном, научной направленности)https://ask3.ru/answer2questionТоварный сопоставитель (Сервис сравнения и выбора товаров) ✰✰
✰ https://ask3.ru/product2collationПартнерыhttps://comrades.ask3.ru


Совет. Чтобы искать на странице, нажмите Ctrl+F или ⌘-F (для MacOS) и введите запрос в поле поиска.
Arc.Ask3.ru: далее начало оригинального документа

Сравнение языков программирования (базовые инструкции) — Википедия Jump to content

Сравнение языков программирования (базовые инструкции)

Из Википедии, бесплатной энциклопедии

В этой статье сравнивается большое количество языков программирования путем таблицы их типов данных , их выражений , операторов и объявлений синтаксиса , а также некоторых общих интерфейсов операционной системы.

Условные обозначения этой статьи [ править ]

Вообще, где , были или var — это то, как представляются имена переменных или другие нелитеральные значения, которые должен интерпретировать читатель. Остальное — буквальный код. Гийеме ( « и ») заключайте необязательные разделы. Tab ↹ указывает на необходимый отступ (пробелы).

По умолчанию таблицы не сортируются лексикографически по возрастанию по названию языка программирования, и некоторые языки имеют записи в одних таблицах, но не в других.

Идентификаторы типа [ править ]

Целые числа [ править ]

8 бит ( байт ) 16 бит ( короткое целое число ) 32 бит 64 бита ( длинное целое число ) Размер слова Произвольная точность ( bignum )
Подписано Без подписи Подписано Без подписи Подписано Без подписи Подписано Без подписи Подписано Без подписи
Есть [1] range -2**7 .. 2**7 - 1[Дж] range 0 .. 2**8 - 1[Дж] или mod 2**8[к] range -2**15 .. 2**15 - 1[Дж] range 0 .. 2**16 - 1[Дж] или mod 2**16[к] range -2**31 .. 2**31 - 1[Дж] range 0 .. 2**32 - 1[Дж] или mod 2**32[к] range -2**63 .. 2**63 - 1[Дж] mod 2**64[к] Integer[Дж] range 0 .. 2**Integer'Size - 1[Дж] или mod Integer'Size[к]
АЛГОЛ 68 (переменная ширина) short short int[с] short int[с] int[с] long int[с] int[с] long long int[а] [г]
bytes и bits
C ( C99 фиксированной ширины) int8_t uint8_t int16_t uint16_t int32_t uint32_t int64_t uint64_t intptr_t[с] size_t[с]
C++ ( С++11 фиксированной ширины)
C ( C99 переменной ширины) signed char unsigned char short[с] unsigned short[с] long[с] unsigned long[с] long long[с] unsigned long long[с] int[с] unsigned int[с]
C++ ( C++11 с переменной шириной)
Цель-C ( Какао ) signed char или int8_t unsigned char или uint8_t short или int16_t unsigned short или uint16_t int или int32_t unsigned int или uint32_t long long или int64_t unsigned long long или uint64_t NSInteger или long NSUInteger или unsigned long
С# sbyte byte short ushort int uint long ulong IntPtr UIntPtr System.Numerics.BigInteger
(.NET 4.0)
Джава byte char[б] java.math.BigInteger
Идти int8 uint8 или byte int16 uint16 int32 uint32 int64 uint64 int uint big.Int
Ржавчина i8 u8 i16 u16 i32 u32 i64 u64 isize usize
Быстрый Int8 UInt8 Int16 UInt16 Int32 UInt32 Int64 UInt64 Int UInt
Д byte ubyte short ushort int uint long ulong BigInt
Общий Лисп [2] (signed-byte 8) (unsigned-byte 8) (signed-byte 16) (unsigned-byte 16) (signed-byte 32) (unsigned-byte 32) (signed-byte 64) (unsigned-byte 64) bignum
Схема
ИСЛИСП [3] bignum
Паскаль ( ФПК ) shortint byte smallint word longint longword int64 qword integer cardinal
Visual Basic Byte Integer Long
Визуальный Бейсик .NET SByte Short UShort Integer UInteger Long ULong System.Numerics.BigInteger
(.NET 4.0)
FreeBasic Byte или Integer<8> UByte или UInteger<8> Short или Integer<16> UShort или UInteger<16> Long или Integer<32> ULong или UInteger<32> LongInt или Integer<64> ULongInt или UInteger<64> Integer UInteger
Питон 2.x int long
Питон 3.x int
Сленг
Фортран INTEGER(KIND = n)[ф] INTEGER(KIND = n)[ф] INTEGER(KIND = n)[ф] INTEGER(KIND = n)[ф]
PHP int[м] int[м] [Это]
Перл 5 [д] [д] [д] [д] [д] Math::BigInt
Раку int8 uint8 int16 uint16 int32 uint32 int64 uint64 Int
Рубин Fixnum Bignum
Эрланг [н] integer() integer()[О]
Скала Byte Short Char[л] Int Long scala.math.BigInt
Сид7 integer bigInteger
Болтовня SmallInteger[я] LargeInteger[я]
Windows PowerShell
OCaml int32 int64 int или nativeint open Big_int;; или big_int
Ф# sbyte byte int16 uint16 int32 или int uint32 uint64 nativeint unativeint bigint
Стандартный ML Word8.word Int32.int Word32.word Int64.int Word64.word int word LargeInt.int или
IntInf.int
Хаскелл ( 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
Эйфелева INTEGER_8 NATURAL_8 INTEGER_16 NATURAL_16 INTEGER_32 NATURAL_32 INTEGER_64 NATURAL_64 INTEGER NATURAL
КОБОЛ [час] BINARY-CHAR «SIGNED» BINARY-CHAR UNSIGNED BINARY-SHORT «SIGNED» BINARY-SHORT UNSIGNED BINARY-LONG «SIGNED» BINARY-LONG UNSIGNED BINARY-DOUBLE «SIGNED» BINARY-DOUBLE UNSIGNED
Математика Integer
Вольфрам Язык Integer
  • ^ Стандартные константы a int shorts и int lengths можно использовать для определения количества shortпесок longs может быть полезно иметь префикс short int и long int. Реальные размеры short int, int, и long int доступны как константы short max int, max int, и long max int и т. д.
  • ^ b Обычно используется для символов.
  • ^ c Языки ALGOL 68, C и C++ не определяют точную ширину целочисленных типов. short, int, longи ( C99 , C++11 ) long long, поэтому они зависят от реализации. В С и С++ short, long, и long longтипы должны иметь ширину не менее 16, 32 и 64 бита соответственно, но может быть и больше. int Тип должен быть по крайней мере такой же ширины, как short и максимум такой же ширины, как long, и обычно представляет собой ширину слова на процессоре машины (т. е. на 32-битной машине она часто имеет ширину 32 бита; на 64-битных машинах она иногда составляет 64 бита). С99 и С++11 [ нужна цитата ] также определить [u]intN_tтипы точной ширины в заголовке stdint.h . см. в разделе Синтаксис C#Целочисленные типы Дополнительную информацию . Кроме того, типы size_t и ptrdiff_t определяются в зависимости от размера адреса для хранения целых чисел без знака и знака, достаточно больших для обработки индексов массива и разницы между указателями.
  • ^d В Perl 5 нет отдельных типов. Целые числа, числа с плавающей запятой, строки и т. д. считаются «скалярами».
  • ^e В PHP есть две библиотеки произвольной точности. Библиотека BCMath просто использует строки в качестве типа данных. Библиотека GMP использует внутренний тип «ресурса».
  • ^ f Значение n обеспечивается SELECTED_INT_KIND[4] внутренняя функция.
  • ^ g Вариант выполнения ALGOL 68 G --precision "number" может установить точность для long long ints до необходимого «числа» значащих цифр. Стандартные константы long long int width и long long max int может использоваться для определения фактической точности.
  • ^h COBOL позволяет указать требуемую точность и автоматически выбирает доступный тип, способный представлять указанную точность. " PIC S9999", например, потребуется переменная со знаком с точностью до четырех десятичных цифр. Если указано как двоичное поле, на большинстве платформ будет выбран 16-битный тип со знаком.
  • ^i Smalltalk автоматически выбирает подходящее представление для целых чисел. Обычно присутствуют два представления: одно для целых чисел, соответствующих собственному размеру слова за вычетом любого бита тега ( SmallInteger ) и один, поддерживающий целые числа произвольного размера ( Большое целое число ). Арифметические операции поддерживают полиморфные аргументы и возвращают результат в наиболее подходящем компактном представлении.
  • ^j Типы диапазонов Ada проверяются на предмет нарушений границ во время выполнения (а также во время компиляции статических выражений). Нарушения границ во время выполнения вызывают исключение «ошибка ограничения». Диапазоны не ограничиваются степенями двойки. Обычно предопределенными целочисленными подтипами являются: Положительные ( range 1 .. Integer'Last) и Натуральный ( range 0 .. Integer'Last). Short_Short_Integer (8 бит), Short_Integer (16 бит) и Long_Integer(64 бита) также обычно предопределены, но не требуются стандартом Ada. Проверки во время выполнения можно отключить, если производительность важнее проверок целостности.
  • ^k Типы Ada по модулю реализуют арифметику по модулю во всех операциях, т. е. нарушения диапазона невозможны. Модули не ограничиваются степенями двойки.
  • ^l Обычно используется для таких символов, как char в Java.
  • int в PHP имеет ту же ширину, что и long тип C есть в этой системе. [с]
  • ^n Erlang является динамически типизированным. Идентификаторы типов обычно используются для указания типов полей записи, а также типов аргументов и возвращаемых значений функций. [5]
  • ^o Когда оно превышает одно слово. [6]

Плавающая точка [ править ]

Одинарная точность Двойная точность Другая точность Зависит от процессора
Есть [1] Float Long_Float
АЛГОЛ 68 real[а] long real[а] short real, long long real, и т. д. [д]
С float[б] double long double[ф]
С++ (СТЛ)
Цель-C ( Какао ) CGFloat
С# float
Джава
Идти float32 float64
Ржавчина f32 f64
Быстрый Float или Float32 Double или Float64 Float80[г] CGFloat
Д float double real
Общий Лисп single-float double-float float, short-float, long-float
Схема
ИСЛИСП
Паскаль ( ФПК ) single double real
Visual Basic Single Double
Визуальный Бейсик .NET
Содзё
Питон float
JavaScript Number[7]
Сленг
Фортран REAL(KIND = n)[с]
PHP float
Перл
Раку num32 num64 Num
Рубин Float
Скала Float Double
Сид7 float
Болтовня Float Double
Windows PowerShell
OCaml float
Ф# float32
Стандартный ML real
Хаскелл ( GHC ) Float Double
Эйфелева REAL_32 REAL_64
КОБОЛ FLOAT-BINARY-7[Это] FLOAT-BINARY-34[Это] FLOAT-SHORT, FLOAT-LONG, FLOAT-EXTENDED
Математика Real
  • ^ Стандартные константы a real shorts и real lengths можно использовать для определения количества shortпесок longs может быть полезно иметь префикс short real и long real. Реальные размеры short real, real, и long real доступны как константы short max real, max real и long max real и т. д. С константами short small real, small real и long small real доступно для машины каждого типа epsilon .
  • ^b объявления одинарной точности часто не соблюдаются
  • ^ c Значение n обеспечивается SELECTED_REAL_KIND[8] внутренняя функция.
  • ^ d Вариант выполнения ALGOL 68 G --precision "number" может установить точность для long long reals до необходимого «числа» значащих цифр. Стандартные константы long long real width и long long max real может использоваться для определения фактической точности.
  • ^e Эти типы с плавающей запятой IEEE будут представлены в следующем стандарте COBOL.
  • ^f Тот же размер, что и double во многих реализациях.
  • ^g Swift поддерживает 80-битный тип с плавающей запятой расширенной точности , что эквивалентно long double на языках Си.

Комплексные числа [ править ]

Целое число Одинарная точность Двойная точность Половинная и четверная точность и т. д.
Есть [1] Complex[б] Complex[б] Complex[б]
АЛГОЛ 68 compl long compl и т. д. short compl и т. д. и long long compl и т. д.
С ( С99 ) [9] float complex double complex
С++ (СТЛ) std::complex<float> std::complex<double>
С# System.Numerics.Complex
(.NET 4.0)
Джава
Идти complex64 complex128
Д cfloat cdouble
Цель-C
Общий Лисп (комплексное целое число) (сложный однопоплавковый) (сложный двухпоплавковый) сложный
Схема
Паскаль
Visual Basic
Визуальный Бейсик .NET System.Numerics.Complex
(.NET 4.0)
Перл Math::Complex
Раку complex64 complex128 Complex
Питон complex
JavaScript
Сленг
Фортран COMPLEX(KIND = n)[а]
Рубин Complex Complex
Скала
Сид7 complex
Болтовня Complex Complex Complex
Windows PowerShell
OCaml Complex.t
Ф# System.Numerics.Complex
(.NET 4.0)
Стандартный ML
Хаскелл ( GHC ) Complex.Complex Float Complex.Complex Double
Эйфелева
КОБОЛ
Математика Complex Complex
  • ^ а Значение n обеспечивается SELECTED_REAL_KIND[8] внутренняя функция.
  • ^b Универсальный тип, экземпляр которого можно создать с помощью любого базового типа с плавающей запятой.

Другие типы переменных [ править ]

Текст логическое значение Перечисление Объект / Универсальный
Характер Нить [а]
Есть [1] Character String, Bounded_String, Unbounded_String Boolean (item1, item2, ...) tagged null record
АЛГОЛ 68 char string, bytes bool, bits - - Определяемые пользователем
С ( С99 ) char, wchar_t bool[б] enum «name» { item1, item2, ... }; void *
С++ (СТЛ) «std::»string
Цель-C unichar NSString * BOOL id
С# char string bool enum name { item1« = value», item2« = value», ... } объект
Джава String boolean enum name { item1, item2, ... } Object
Идти byte, rune string bool const (
   item1 = iota
   item2
   ...
)
interface{}
Ржавчина char String bool enum name { item1« = value», item2« = value», ... } std::any::Any
Быстрый Character String Bool enum name { case item1, item2, ... } Any
Д char string bool enum name { item1, item2, ... } std.variant.Variant
Общий Лисп character string boolean (member item1 item2 ...) t
Схема
ИСЛИСП
Паскаль (ISO) char boolean ( item1, item2, ... )
Объектный Паскаль ( Делфи ) string variant
Visual Basic String Boolean Enum name
   item1 «= value»
   item2 «= value»
   ...

End Enum
[[Variant type|Variant]]
Визуальный Бейсик .NET Char Object
Содзё Object или Variant
Питон [д] str bool from enum import Enum
class Name(Enum):
   item1 = value
   item2 = value
   ...
object
JavaScript [д] String Boolean Object
Сленг
Фортран CHARACTER(LEN = *) CHARACTER(LEN = :), allocatable LOGICAL(KIND = n)[ф] CLASS(*)
PHP [д] string bool (объявление типа опущено)
Перл [д] UNIVERSAL
Раку Char Str Bool enum name<item1 item2 ...>
enum name <<:item1(value) :item2(value) ..>>
Mu
Рубин [д] String Object[с] Object
Скала Char String Boolean object name extends Enumeration {
   val item1, item2, ... = Value
}
Any
Сид7 char string boolean const type: name is new enum
   item1,
   item2,
   ...
end enum;
Windows PowerShell
OCaml char string bool [Это]
Ф# type name = item1 = value |item2 = value | ... obj
Стандартный ML [Это]
Хаскелл ( GHC ) Char String Bool [Это]
Эйфелева CHARACTER STRING BOOLEAN ANY
КОБОЛ PIC X PIC X(string length) или PIC X«X...» PIC 1«(number of digits или PIC 1«1...» OBJECT REFERENCE
Математика [д] String
  • ^a , в частности, строки произвольной длины и автоматически управляемые.
  • ^b Этот язык представляет логическое значение как целое число, где false представлено как нулевое значение, а true - как ненулевое значение.
  • ^c Все значения оцениваются как true или false. Все в TrueClass оценивается как true и все в FalseClass оценивается как ложь.
  • ^d В этом языке нет отдельного типа символов. Символы представлены в виде строк длиной 1.
  • ^e Перечисления в этом языке представляют собой алгебраические типы и содержат только нулевые конструкторы.
  • ^ f Значение n обеспечивается SELECTED_INT_KIND[4] внутренняя функция.

Производные типы [ править ]

Массив [ править ]

массив фиксированного размера массив динамического размера
одномерный массив многомерный массив одномерный массив многомерный массив
Есть [1] array (<first> .. <last>) of <type>
или
array (<discrete_type>) of <type>
array (<first1> .. <last1>, <first2> .. <last2>, ...) of <type>
или
array (<discrete_type1>, <discrete_type2>, ...) of <type>
array (<discrete_type> range <>) of <type> array (<discrete_type1> range <>, <discrete_type2> range <>, ...) of <type>
АЛГОЛ 68 [first:last]«modename»
или просто:
[size]«modename»
[first1:last1, first2:last2]«modename»
или
[first1:last1][first2:last2]«modename»
и т. д.
flex[first:last]«modename»
или просто:
flex[size]«modename»
flex[first1:last1, first2:last2]«modename»
или
flex[first1:last1]flex[first2:last2]«modename» etc.
С ( С99 ) type name[size][а] type name[size1][size2][а] type *name
или внутри блока:
int n = ...; type name[n]
С++ (СТЛ) «std::»array<type, size>(С++11) «std::»vector<type>
С# type[] type[,,...] System.Collections.ArrayList
или
System.Collections.Generic.List<type>
Джава type[][б] type[][]...[б] ArrayList or ArrayList<type>
Д type[size] type[size1][size2] type[]
Идти [size]type [size1][size2]...type []type [][]type
Ржавчина [type; size] [[type; size1]; size2] Vec<type> Vec<Vec<type>>
Быстрый [type] или Array<type> [[type]] или Array<Array<type>>
Цель-C NSArray NSMutableArray
JavaScript Array[д]
Общий Лисп (simple-array type (dimension)) (simple-array type (dimension1 dimension2)) (array type (dimension)) (array type (dimension1 dimension2))
Схема
ИСЛИСП
Паскаль array[first..last] of type[с] array[first1..last1] of array[first2..last2] ... of type[с]
или
array[first1..last1, first2..last2, ...] of type[с]
Объектный Паскаль ( Делфи ) array of type array of array ... of type
Visual Basic Dim x(last) As type Dim x(last1, last2,...) As type
Визуальный Бейсик .NET type() type(,,...) System.Collections.ArrayList
или
System.Collections.Generic.List(Of type)
Питон list
Сленг x = type[size]; x = type[size1, size2, ...];
Фортран type :: name(size) type :: name(size1, size2,...) type, ALLOCATABLE :: name(:) type, ALLOCATABLE :: name(:,:,...)
PHP array
Перл
Раку Array[type] or Array of type
Рубин x = Array.new(size1){ Array.new(size2) } Array
Скала Array[type] Array[...[Array[type]]...] ArrayBuffer[type]
Сид7 array type
или
array [idxType] type
array array type
или
array [idxType] array [idxType] type
array type
или
array [idxType] type
array array type
или
array [idxType] array [idxType] type
Болтовня Array OrderedCollection
Windows PowerShell type[] type[,,...]
OCaml type array type array ... array
Ф# type []
или
type array
type [,,...] System.Collections.ArrayList
или
System.Collections.Generic.List<type>
Стандартный ML type vector or type array
Хаскелл ( GHC ) x = Array.array (0, size-1) list_of_association_pairs x = Array.array ((0, 0,...), (size1-1, size2-1,...)) list_of_association_pairs
КОБОЛ level-number type OCCURS size «TIMES». определение одномерного массива... level-number type OCCURS min-size TO max-size «TIMES» DEPENDING «ON» size.[Это]
  • ^a В большинстве выражений (кроме sizeof и &операторы), значения типов массива в C автоматически преобразуются в указатель на его первый аргумент. См. синтаксис C#Массивы для получения дополнительной информации о синтаксисе и операциях с указателями.
  • ^ b C-подобный type x[] работает на Java, однако type[] x — предпочтительная форма объявления массива.
  • ^c Поддиапазоны используются для определения границ массива.
  • ^d Массив JavaScript — это особый тип объекта.
  • ^ е DEPENDING ON Предложение в COBOL не создает настоящий массив переменной длины и всегда выделяет максимальный размер массива.

Другие типы [ править ]

Простые составные типы Алгебраические типы данных Союзы
Рекорды кортежа Выражение
Есть [1] type name is «abstract» «tagged» «limited» [record
  field1 : type;
  field2 : type;
  ...
end record | null record]
Любая комбинация записей, объединений и перечислений (а также ссылки на них, позволяющие использовать рекурсивные типы). type name (variation : discrete_type) is record
  case variation is
     when choice_list1 =>
      fieldname1 : type;
      ...
     when choice_list2 =>
      fieldname2 : type;
      ...
     ...
  end case;
end record
АЛГОЛ 68 struct (modename «fieldname», ...); Требуемые типы и операторы могут определяться пользователем. union (modename, ...);
С ( С99 ) struct «name» {type name;...}; union {type name;...};
Цель-C
С++ struct «name» {type name;...};[б] «std::»tuple<type1..typen>
С# struct name {type name;...} (val1, val2, ... )
Джава [а]
JavaScript
Д struct name {type name;...} std.variant.Algebraic!(type,...) union {type name;...}
Идти struct {
  «name» type
  ...
}
Ржавчина struct name {name: type, ...} (val1, val2, ... ) enum name { Foo(types), ...} union name {name: type, ...}
Быстрый struct name {
  
var name «: type»
  ...
}
(«name1:» val1, «name2:» val2, «name3:» val3, ... ) enum name { case Foo«(types)» case Bar «(types... }
Общий Лисп (defstruct name slot-name (slot-name initial-value) (slot-name initial-value :type type) ...) (cons val1 val2)[с]
Схема
ИСЛИСП
Паскаль record
  name: type;
  ...
end
record
  case type of
  value: (types);
  ...
end
Visual Basic
Визуальный Бейсик .NET Structure name
  Dim name As type
  ...
End Structure
(val1, val2, ... )
Питон [а] «(»val1, val2, val3, ... «)»
Сленг struct {name [=value], ...}
Фортран TYPE name
  type
 :: name
  ...
END TYPE
PHP [а]
Перл [д]
Раку [а]
Рубин OpenStruct.new({:name => value})
Скала case class namevar» name: type, ...) (val1, val2, val3, ... ) abstract class name
  case class Fooparameters») extends name
  case class Barparameters») extends name
  ...

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

или комбинация классов Case и объектов Case
Windows PowerShell
OCaml type name = {«mutable» name : type;...} «(»val1, val2, val3, ... «)» type name = Foo «of type» | Bar «of type» | ...
Ф#
Стандартный ML type name = {name : type,...} (val1, val2, val3, ... ) datatype name = Foo «of type» | Bar «of type» | ...
Хаскелл data Name = Constr {name :: type,...} data Name = Foo «types» | Bar «types» | ...
КОБОЛ level-number name type clauses.
  level-number+n name type clauses.
  ...
name REDEFINES variable type.
  • ^a Поддерживаются только классы.
  • ^ б structs в C++ на самом деле являются классами, но имеют общедоступную видимость по умолчанию, а являются также объектами POD . C++11 расширил это, чтобы во многих других случаях классы действовали идентично объектам POD.
  • ^c только пара
  • ^d Хотя в Perl нет записей, поскольку система типов Perl позволяет различным типам данных находиться в массиве, «хэши» (ассоциативные массивы), не имеющие индекса переменной, по сути, будут такими же, как и записи.
  • ^e Перечисления в этом языке представляют собой алгебраические типы и содержат только нулевые конструкторы.

Объявления переменных и констант [ править ]

переменная постоянный введите синоним
Есть [1] identifier : type« := initial_value»[Это] identifier : constant type := final_value subtype identifier is type
АЛГОЛ 68 modename name« := initial_value»; modename name = value; mode synonym = modename;
С ( С99 ) type name« = initial_value»; enum{ name = value }; typedef type synonym;
Цель-C
С++ const type name = value;
С# type name1« = initial_value», name2« = initial_value», ...;
или
var name = initial_value;
const type name = value, name = value, ...;
или
readonly type name = value, name = value, ... ;
using synonym = type;
Д type name« = initial_value»;
или
auto name = value;
const type name = value;
или
immutable type name = value;
alias type synonym;
Джава type name« = initial_value»; final type name = value;
JavaScript var name« = initial_value»; или
let name« = initial_value»; (начиная с ECMAScript 2015)
const name = value; (начиная с ECMAScript 2015)
Идти var name type« = initial_value»
или
name := initial_value
const name «type» = value type synonym type
Ржавчина [ф] 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;
Быстрый var name «: type»« = initial_value» let name «: type» = value typealias synonym = type
Общий Лисп (defparameter name initial-value)
или
(defvar name initial-value)
(defconstant name value) (deftype synonym () 'type)
Схема (define name initial_value)
ИСЛИСП (defglobal name initial_value)
или
(defdynamic name initial_value)
(defconstant name value)
Паскаль [а] name: type« = initial_value» name = value synonym = type
Visual Basic Dim name «As type» См. примечания слева.

Константы используют тот же синтаксис и:

  • использовать Const вместо Dim
  • иметь ограничение только на определенные примитивные типы
    Const name1 «As type» = value, name2 «As type» = value, ...
Визуальный Бейсик .NET [10] Синтаксис объявления переменных VB.NET необычайно сложно точно описать.

Учитывая, что существуют суффиксы идентификаторов («модификаторы»):

  • type_character, доступный в качестве альтернативы As предложение для некоторых примитивных типов данных;
  • nullable_specifier; и
  • array_specifier;

и это

  • а modified_identifier имеет форму identifier«type_character»«nullable_specifier»«array_specifier»;
  • а modified_identifier_list представляет собой разделенный запятыми список двух или более вхождений modified_identifier; и
  • а declarator_list представляет собой список деклараторов, разделенных запятыми, который может иметь форму
    • identifier As object_creation_expression (декларатор инициализатора объекта) ,
    • modified_identifier «As non_array_type«array_rank_specifier»»« = initial_value» (один декларатор) или
    • modified_identifier_list «As «non_array_type««array_rank_specifier»» (множественный декларатор);

действительные операторы декларации имеют форму Dim declarator_list, где для целей семантического анализа преобразовать declarator_list к списку только одиночных деклараторов:

  • The As предложений каждого множественного декларатора распределяется по его modified_identifier_list
  • The As New type... каждого декларатора инициализатора объекта заменяется на As type = New type...

и для чего, для каждого identifier,

  • а type_character и As пункт не оба появляются;
  • если As пункт присутствует,
    • а array_rank_specifier не проявляется ни в виде модификации идентификатора, ни в виде типа As пункт;
  • а unmodified_type можно определить по правилу, что
    • если type_character или As пункт присутствует,
      • unmodified_type это указано такой конструкцией,
    • и что иначе,
      • или Option Infer должен быть включен и identifier должен иметь инициализатор, и в этом случае unmodified_type это инициализатор или
      • Option Strict должен быть выключен, в этом случае unmodified_type является Object;
  • его final_type это его unmodified_type добавляется перед модификаторами;
  • его final_typeявляется допустимым типом; и
  • если initial_value настоящее,
    • или Option Strict включен и initial_value имеет расширяющее преобразование в final_type, или
    • Option Strict выключен и initial_value имеет сужающее преобразование в final_type.

Если Option Explicitвыключен, переменные не требуют явного объявления; они объявляются неявно при использовании: name = initial_value

Imports synonym = type
Содзё Dim name «As type»« = initial_value»
Питон name«: type» = initial_value synonym = type[б]
Кофескрипт name = initial_value
Сленг name = initial_value; typedef struct {...} typename
Фортран type :: name type, PARAMETER :: name = value
PHP $name = initial_value; define("name", value);
const name = value (5.3+)
Перл «my» $name« = initial_value»;[с] use constant name => value;
Раку «my «type»» $name« = initial_value»;[с] «my «type»» constant name = value; ::synonym ::= type
Рубин name = initial_value Name = value synonym = type[б]
Скала var name«: type» = initial_value val name«: type» = value type synonym = type
Windows PowerShell «[type]» $name = initial_value
Баш-оболочка name=initial_value
OCaml let name« : type ref» = ref value[д] let name «: type» = value type synonym = type
Ф# let mutable name «: type» = value
Стандартный ML val name «: type ref» = ref value[д] val name «: type» = value
Хаскелл «name::typename = value type Synonym = type
Форт VARIABLE name (в некоторых системах используется value VARIABLE name вместо) value CONSTANT name
КОБОЛ level-number name type clauses. «0»1 name CONSTANT «AS» value. level-number name type clauses «IS» TYPEDEF.
Математика name=initial_value
  • ^ В Паскале есть блоки объявлений. См. функции .
  • ^b Типы — это обычные объекты, поэтому их можно просто назначать.
  • ^c В Perl ключевое слово «my» помещает переменную в блок.
  • ^d Технически, это не объявляет имя изменяемой переменной — в ML все имена могут быть связаны только один раз; скорее, он объявляет имя , указывающее на «ссылочную» структуру данных, которая представляет собой простую изменяемую ячейку. Затем структуру данных можно прочитать и записать с помощью ! и := операторы соответственно.
  • ^e Если начальное значение не указано, автоматически присваивается недопустимое значение (что вызовет исключение во время выполнения, если оно использовалось до того, как было присвоено допустимое значение). Хотя такое поведение можно подавить, оно рекомендуется в интересах предсказуемости. Если для типа не найдено недопустимое значение (например, в случае неограниченного целочисленного типа), вместо него выбирается допустимое, но предсказуемое значение.
  • ^f В Rust, если начальное значение не задано let или let mutпеременной, и она никогда не присваивается позже, появляется предупреждение «неиспользуемая переменная» . Если значение не указано для const или static или static mutпеременная, есть ошибка. возникает ошибка «глобальные переменные не в верхнем регистре». Для непрописных букв constпеременные. После того как оно определено, static mut переменная может быть присвоена только в unsafe блок или функция.

Поток управления [ править ]

Условные операторы [ править ]

если еще если выбрать случай условное выражение
Есть [1] 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
)

или
(case expression is
  when value_list1 => expression1
  when value_list2 => expression2
  ...
  «when others => expressionn»
)
Сид7 if condition then
  statements
«else
  statements»
end if
if condition1 then
  statements
elsif condition2 then
  statements
...
«else
  statements»
end if
case expression of
  when set1 : statements
  ...
  «otherwise: statements»
end case
Модуль-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
АЛГОЛ 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 )
АЛГОЛ 68
(краткая форма)
( condition | statements «| statements» ) ( condition | statements |: condition | statements ) ( variable | statements,... «| statements» )
АПЛ :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}
С ( С99 ) if (condition) instructions
«else instructions»

instructions может быть отдельным оператором или блоком в форме: { statements }
if (condition) instructions
else if (condition) instructions
...
«else instructions»

или
if (condition) instructions
else { if (condition) instructions }
switch (variable) {
  case case1: instructions «; break;»
  ...
  «default: instructions»
}
condition ? valueIfTrue : valueIfFalse
Цель-C
С++ (СТЛ)
Д
Джава
JavaScript
PHP
С# if (condition) instructions
«else instructions»

instructions может быть отдельным оператором или блоком в форме: { 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»
}

Все непустые регистры должны заканчиваться break или goto caseоператор (то есть им не разрешено переходить к следующему случаю). default случай не обязательно должен идти последним.

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 }»}
Идти if condition {instructions}
«else {instructions
if condition {instructions}
else if condition {instructions}
...
«else {instructions

или
switch {
  case condition: instructions
  ...
  «default: instructions»
}
switch variable {
  case case1: instructions
  ...
  «default: instructions»
}
Быстрый if condition {instructions}
«else {instructions
if condition {instructions}
else if condition {instructions}
...
«else {instructions
switch variable {
  case case1: instructions
  ...
  «default: instructions»
}
Перл if (condition) {instructions}
«else {instructions

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

или
unless (notcondition) {instructions}
elsif (condition) {instructions}
...
«else {instructions
use feature "switch";
...
given (variable) {
  when (case1) { instructions }
  ...
  «default { instructions
}
condition ? valueIfTrue : valueIfFalse
Раку if condition {instructions}
«else {instructions

или
unless notcondition {instructions}
if condition {instructions}
elsif condition {instructions}
...
«else {instructions}
given variable {
  when case1 { instructions }
  ...
  «default { instructions
}
condition ?? valueIfTrue !! valueIfFalse
Рубин 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
Скала 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
Болтовня condition ifTrue:
  trueBlock
«ifFalse:
  falseBlock»
end
condition ifTrue: trueBlock ifFalse: falseBlock
Общий Лисп (when condition
  instructions)

или
(unless condition
  instructions)

или
(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)
или
(cond (test1 value1) (test2 value2) ...))
Схема (when condition instructions)
или
(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)
ИСЛИСП (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)
Паскаль 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

Однострочный, когда instructions являются instruction1 : instruction2 : ...:
If condition Then instructions «Else instructions»
If condition Then
  instructions
ElseIf condition Then
  instructions
...
«Else
  instructions»
End If

Одна линия:
См. примечание о C-подобных языках; тот Else однострочное предложение If оператор может содержать еще одну однострочную строку If заявление.
Select« Case» variable
  Case case_pattern1
     instructions
  ...
  «Case Else
     instructions»
End Select
IIf(condition, valueIfTrue, valueIfFalse)
Визуальный Бейсик .NET If(condition, valueIfTrue, valueIfFalse)
Содзё
Питон [а] if condition :
Tab ↹instructions
«else:
Tab ↹instructions»
if condition :
Tab ↹instructions
elif condition :
Tab ↹instructions
...
«else:
Tab ↹instructions»
Питон 3.10+:
match variable:
Tab ↹case case1:
Tab ↹Tab ↹instructions
Tab ↹case case2:
Tab ↹Tab ↹instructions
Питон 2.5+:
valueIfTrue if condition else valueIfFalse
Сленг if (condition) { instructions } «else { instructions if (condition) { instructions } else if (condition) { instructions } ... «else { instructions switch (variable) { case case1: instructions } { case case2: instructions } ...
Фортран 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
Форт 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
Ф# Режим упрощенного синтаксиса:

Либо в одну строку, либо с отступом, как показано ниже: if condition then
Tab ↹instructions
«else
Tab ↹instructions»

Режим подробного синтаксиса:
То же, что и стандартное ML.

Режим упрощенного синтаксиса:
Либо в одну строку, либо с отступом, как показано ниже:
if condition then
Tab ↹instructions
elif condition then
Tab ↹instructions
...
«else
Tab ↹instructions»

Режим подробного синтаксиса:
То же, что и стандартное ML.
Стандартный 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»
[б]
Хаскелл ( GHC ) if condition then expression else expression
или
when condition (do instructions)
или
unless notcondition (do instructions)
result | condition = expression
  | condition = expression
  | otherwise = expression
case value of {
  pattern1 -> expression;
  pattern2 -> expression;
  ...
  «_ -> expression»
}
[б]
Баш-оболочка 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
Кофескрипт if condition then expression «else expression»
или
if condition
  expression

«else
  expression»

или
expression if condition
или
unless condition
  expression
«else
  expression»

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

«else
  expression»

или
unless condition
  expression
else unless condition
  expression

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

или
switch expression
  when condition
     expression
  «else
     expression»
Все условия являются выражениями.
КОБОЛ IF condition «THEN»
  expression
«ELSE
  expression».
[д]
EVALUATE expression «ALSO expression...»
  WHEN case-or-condition «ALSO case-or-condition...»
     expression
  ...

  «WHEN OTHER
     expression»
END-EVALUATE
Ржавчина if condition {
  expression
}« else {
  expression
if condition {
  expression
} else if condition {
  expression
}« else {
  expression
}»
match variable {
  pattern1 => expression,
  pattern2 => expression,
  pattern3 => expression,
  «_ => expression»
}
[б] [Это]
Все условия являются выражениями
если еще если выбрать случай условное выражение
  • ^a Одну инструкцию можно записать в одной строке после двоеточия. Несколько инструкций группируются в блок , который начинается с новой строки (отступ обязателен). Синтаксис условного выражения не подчиняется этому правилу.
  • ^b Это сопоставление с образцом , похожее на случай выбора, но не то же самое. Обычно он используется для деконструкции алгебраических типов данных .
  • ^c В языках семейства Паскаль точка с запятой не является частью оператора. Это разделитель между утверждениями, а не терминатор.
  • ^ д END-IF может использоваться вместо точки в конце.
  • ^e В Rust запятая ( ,) в конце ветви совпадения можно опустить после последней ветви совпадения или после любой ветви совпадения, в которой выражение является блоком (возможно, заканчивается пустыми скобками соответствия {}).

Операторы цикла [ править ]

пока цикл делать цикл while (контролируемый счет) для цикла для каждого
Есть [1] 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

или
(for [all | some] [in | of] [first .. last | discrete_type | iterator] => predicate)[б]
АЛГОЛ 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
АПЛ :While condition
  statements
:EndWhile
:Repeat
  statements
:Until condition
:For var«s» :In list
  statements
:EndFor
:For var«s» :InEach list
  statements
:EndFor
С ( С99 ) instructions может быть отдельным оператором или блоком в форме: { statements }
while (condition) instructions
do instructions while (condition); for («type» i = first; i <= last; i++) instructions
Цель-C for (type item in set) instructions
С++ (СТЛ) «std::»for_each(start, end, function)
Начиная с С++ 11 :
for (type item : set) instructions
С# foreach (type item in set) instructions
Джава for (type item : set) instructions
JavaScript for (var i = first; i <= last; i++) instructions Начиная с EcmaScript 2015: [11]

for (var item of set) instructions

PHP foreach (range(first, last) as $i) instructions
или
for ($i = first; $i <= last; $i++) instructions
foreach (set as item) instructions
или
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
Идти for condition { instructions } for i := first; i <= last; i++ { instructions } for key, item := range set { instructions }
Быстрый while condition { instructions } 2.х:
repeat { instructions } while condition
1.х:
do { instructions } while condition
for i = first ... last { instructions }
или
for i = first ..< last+1 { instructions }
или
for var i = first; i <= last; i++ { instructions }
for item in set { instructions }
Перл while (condition) { instructions }
или
until (notcondition) { instructions }
do { instructions } while (condition)
или
do { instructions } until (notcondition)
for«each» «$i» (first .. last) { instructions }
или
for ($i = first; $i <= last; $i++) { instructions }
for«each» «$item» (set) { instructions }
Раку while condition { instructions }
или
until notcondition { instructions }
repeat { instructions } while condition
или
repeat { instructions } until notcondition
for first..last -> $i { instructions }
или
loop ($i = first; $i <=last; $i++) { instructions }
for set« -> $item» { instructions }
Рубин while condition
  instructions
end

или
until notcondition
  instructions
end
begin
  instructions
end while condition

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

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

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

или
set.each { |item| instructions }
Баш-оболочка while condition ;do
  instructions
done

или
until notcondition ;do
  instructions
done
for ((i = first; i <= last; ++i)) ; do
  instructions
done
for item in set ;do
  instructions
done
Скала while (condition) { instructions } do { instructions } while (condition) for (i <- first to last «by 1») { instructions }
или
first to last «by 1» foreach (i => { instructions })
for (item <- set) { instructions }
или
set foreach (item => { instructions })
Болтовня conditionBlock whileTrue:
  loopBlock
loopBlock doWhile:
  conditionBlock
first to: last do:
  loopBlock
collection do:
  loopBlock
Общий Лисп (loop
  while condition
  do
  instructions)

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

или
(dotimes (i N)
  instructions)

или
(do ((i first (1+ i))) ((>=i last))

  instructions)
(loop
  for item in list
  do
  instructions)

или
(loop
  for item across vector
  do
  instructions)

или
(dolist (item list)
  instructions)

или
(mapc function list)
или
(map type function sequence)
Схема (do () (notcondition) instructions)
или
(let loop () (if condition (begin instructions (loop))))
(let loop () (instructions (if condition (loop)))) (do ((i first (+ i 1))) ((>= i last)) instructions)
или
(let loop ((i first)) (if (< i last) (begin instructions (loop (+ i 1)))))
(for-each (lambda (item) instructions) list)
ИСЛИСП (while condition instructions) (tagbody loop instructions (if condition (go loop)) (for ((i first (+ i 1))) ((>= i last)) instructions) (mapc (lambda (item) instructions) list)
Паскаль 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

или
Do Until notcondition
  instructions
Loop

или
While condition
  instructions
Wend
(Visual Basic .NET использует End While вместо)
Do
  instructions
Loop While condition

или
Do
  instructions
Loop Until notcondition
i должно быть заявлено заранее.

For i = first To last «Step
  instructions

Next i

For Each item In set
  instructions
Next item
Визуальный Бейсик .NET For i« As type» = first To last« Step
  instructions

Next« i»
[а]
For Each item« As type» In set
  instructions
Next« item»
Содзё While condition
  instructions
Wend
Do Until notcondition
  instructions
Loop

или
Do
  instructions
Loop Until notcondition
Питон while condition :
Tab ↹instructions
«else:
Tab ↹instructions»
Питон 3.x:
for i in range(first, last+1):
Tab ↹instructions
«else:
Tab ↹instructions»

Питон 2.x:
for i in xrange(first, last+1):
Tab ↹instructions
«else:
Tab ↹instructions»
for item in set:
Tab ↹instructions
«else:
Tab ↹instructions»
Сленг 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»
Фортран DO WHILE (condition)
  instructions
ENDDO
DO
  instructions
  IF (condition) EXIT
ENDDO
DO I = first,last
  instructions
ENDDO
Форт BEGIN «instructions» condition WHILE instructions REPEAT BEGIN instructions condition UNTIL limit start DO instructions LOOP
OCaml while condition do instructions done for i = first to last do instructions done Array.iter (fun item -> instructions) array
или
List.iter (fun item -> instructions) list
Ф# while condition do
Tab ↹instructions
for i = first to last do
Tab ↹instructions
foritem in set do
Tab ↹instructions

или
Seq.iter (fun item -> instructions) set
Стандартный ML while condition do ( instructions ) Array.app (fn item => instructions) array
или
app (fn item => instructions) list
Хаскелл ( GHC ) Control.Monad.forM_ [first..last] (\i -> do instructions) Control.Monad.forM_list (\item -> do instructions)
Эйфелева from
  setup
until
  condition
loop
  instructions
end
Кофескрипт while condition
  expression

или
expression while condition
или
while condition then expression
или
until condition
  expression

или
expression until condition
или
until expression then condition
for i in [first..last]
  expression

или
for i in [first..last] then expression
или
expression for i in [first..last]
for item in set
  expression

или
for item in set then expression
или
expression for item in set
КОБОЛ PERFORM procedure-1 «THROUGH procedure-2» ««WITH» TEST BEFORE» UNTIL condition[с]
или
PERFORM ««WITH» TEST BEFORE» UNTIL condition
  expression
END-PERFORM
PERFORM procedure-1 «THROUGH procedure-2» «WITH» TEST AFTER UNTIL condition[с]
или
PERFORM «WITH» TEST AFTER UNTIL condition
  expression
END-PERFORM
PERFORM procedure-1 «THROUGH procedure-2» VARYING i FROM first BY increment UNTIL i > last[д]
или
PERFORM VARYING i FROM first BY increment UNTIL i > last
  expression
END-PERFORM
[д]
Ржавчина while condition {
  expression
}
loop {
  expression
     if condition {
      break;
  }
}
for i in first..last+1 {
  expression
}

или
for i in first..=last {
  expression
}
for item in set {
  expression
}
[Это]
или
set.into_iter().for_each(|item| expression);[Это]
  • " step n" используется для изменения интервала цикла. Если " step" опущен, то интервал цикла равен 1.
  • ^b Это реализует квантор универсальности («для всех» или « "), а также квантор существования ("существует" или " ").
  • ^ с THRU может использоваться вместо THROUGH.
  • ^ д «IS» GREATER «THAN» может использоваться вместо >.
  • ^e Тип выражения набора должен реализовывать признак std::iter::IntoIterator.

Исключения [ править ]

бросать обработчик утверждение
Есть [1] 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
АПЛ «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
С ( С99 ) longjmp(state, exception); switch (setjmp(state)) { case 0: instructions break; case exception: instructions ... } assert(condition);
С++ throw exception; try { instructions } catch «(exception)» { instructions } ...
С# try { instructions } catch «(exception« name»)» { instructions } ... «finally { instructions System.Diagnostics.Debug.Assert(condition);
или
System.Diagnostics.Trace.Assert(condition);
Джава 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);
Сленг try { instructions } catch «exception» { instructions } ... «finally { instructions ?
Windows PowerShell trap «[exception]» { instructions } ... instructions
или
try { instructions } catch «[exception]» { instructions } ... «finally { instructions
[Debug]::Assert(condition)
Цель-C @throw exception; @try { instructions } @catch (exception) { instructions } ... «@finally { instructions NSAssert(condition, description);
Быстрый throw exception (2.х) do { try expression ... instructions } catch exception { instructions } ... (2.х) assert(condition«, description»)
Перл die exception; eval { instructions }; if ($@) { instructions } ?
Раку try { instructions CATCH { when exception { instructions } ...}} ?
Рубин raise exception begin
  instructions
rescue exception
  instructions
...
«else
  instructions»
«ensure
  instructions»
end
Болтовня exception raise instructionBlock on: exception do: handlerBlock assert: conditionBlock
Общий Лисп (error "exception")
или
(error
  type
  arguments)

или
(error (make-condition
  type
  arguments))
(handler-case
  (progn instructions)
  (exception instructions)
  ...)

или
(handler-bind
  (condition
     (lambda
     instructions
     «invoke-restart restart args»))
...)
[а]
(assert condition)
или
(assert condition
  «(place)
  «error»»)

или
(check-type var type)
Схема ( Р 6 РС ) (raise exception) (guard (con (condition instructions) ...) instructions) ?
ИСЛИСП (error "error-string" objects)
или
(signal-condition condition continuable)
(with-handler
  handler form*
)
?
Паскаль 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
'*** Попробуйте класс *** 
 Private   mstrDescription   As   String 
 Private   mlngNumber   As   Long 

 Public   Sub   Catch  () 
     mstrDescription   =   Err  .   Описание 
     mlngNumber   =   Err  .  Number 
 End   Sub 

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

 Public   Property   Get   Description  ()   As   StringDescription 
      Общее свойство   =   mstrDescription 
 End   Property 
[12]
Debug.Assert condition
Визуальный Бейсик .NET Throw exception
или
Error errorcode
Try
  instructions
Catch« name As exception»« When condition»
  instructions
...
«Finally
  instructions»
End Try
System.Diagnostics.Debug.Assert(condition)
или
System.Diagnostics.Trace.Assert(condition)
Содзё Raise exception Try
  instructions
Catch «exception»
  instructions
...
«Finally
  instructions»
End Try
Питон raise exception try:
Tab ↹instructions
except «exception»:
Tab ↹instructions
...
«else:
Tab ↹instructions»
«finally:
Tab ↹instructions»
assert condition
Фортран
Форт code THROW xt CATCH ( code or 0 )
OCaml raise exception try expression with pattern -> expression ... assert condition
Ф# try expression with pattern -> expression ...
или
try expression finally expression
Стандартный ML raise exception «arg» expression handle pattern => expression ...
Хаскелл ( GHC ) throw exception
или
throwError expression
catch tryExpression catchExpression
или
catchError tryExpression catchExpression
assert condition expression
КОБОЛ RAISE «EXCEPTION» exception USE «AFTER» EXCEPTION OBJECT class-name.
или
USE «AFTER» EO class-name.
или
USE «AFTER» EXCEPTION CONDITION exception-name «FILE file-name».
или
USE «AFTER» EC exception-name «FILE file-name».
Ржавчина Нет [13] assert!(condition)
  • ^ Common Lisp позволяет with-simple-restart, restart-case и restart-bind определить перезапуск для использования с invoke-restart. Необработанные условия могут привести к тому, что реализация покажет пользователю меню перезапуска перед разматыванием стека.
  • ^b Неперехваченные исключения распространяются на самое внутреннее динамически включающее выполнение. Исключения не распространяются на задачи (если только эти задачи в данный момент не синхронизированы во время рандеву).

Другие операторы потока управления [ править ]

выходной блок (перерыв) продолжать этикетка ветка ( перейти ) возвращаемое значение от генератора
Есть [1] exit «loop_name» «when condition» label: goto label
АЛГОЛ 68 value exit; ... do statements; skip exit; label: statements od label: ... go to label; ...
goto label; ...
label; ...
yield(value)

( Перезвонить ) [14]

АПЛ :Leave :Continue label: label
или
:GoTo label
С ( С99 ) break; continue; label: goto label;
Цель-C
С++ (СТЛ)
Д
С# yield return value;
Джава break «label»; continue «label»;
JavaScript yield value«;»
PHP break «levels»; continue «levels»; goto label; yield «key =>» value;
Перл last «label»; next «label»;
Раку
Идти break «label» continue «label» goto label
Быстрый break «label» continue «label»
Баш-оболочка break «levels» continue «levels»
Общий Лисп (return)
или
(return-from block)
или
(loop-finish)
(tagbody tag
  ...
  tag
...)
(go tag)
Схема
ИСЛИСП (return-from block) (tagbody tag
  ...
  tag
...)
(go tag)
Паскаль (ISO) label:[а] goto label;
Паскаль ( ФПК ) break; continue;
Visual Basic Exit blockАльтернативно, для методов,
Return
label: GoTo label
Содзё Continue block
Визуальный Бейсик .NET Yield value
Питон break continue yield value
РПГ IV LEAVE; ITER;
Сленг break; continue;
Фортран EXIT CYCLE label[б] GOTO label
Рубин break next
Windows PowerShell break «label» continue
OCaml
Ф#
Стандартный ML
Хаскелл ( GHC )
КОБОЛ EXIT PERFORM или EXIT PARAGRAPH или EXIT SECTION или EXIT. EXIT PERFORM CYCLE label «SECTION». GO TO label
  • ^ В Паскале есть блоки объявлений. См. функции .
  • Метка ^b должна представлять собой число от 1 до 99999.

Функции [ править ]

См. рефлексивное программирование для вызова и объявления функций по строкам.

вызов функции базовая/пустая функция функция, возвращающая значение необходимая основная функция
Есть [1] foo «(parameters)» procedure foo «(parameters)» is begin statements end foo function foo «(parameters)» return type is begin statements end foo
АЛГОЛ 68 foo «(parameters)»; proc foo = «(parameters)» void: ( instructions ); proc foo = «(parameters)» rettype: ( instructions ...; retvalue );
АПЛ «parameters» foo parameters foo←{ statements } foo←{ statements }
С ( С99 ) foo(«parameters») void foo(«parameters») { instructions } type foo(«parameters») { instructions ... return value; } «global declarations»
int main(«int argc, char *argv[]») {
  instructions
}
Цель-C
С++ (СТЛ)
Джава public static void main(String[] args) { instructions }
или
public static void main(String... args) { instructions }
Д int main(«char[][] args») { instructions}
или
int main(«string[] args») { instructions}
или
void main(«char[][] args») { instructions}
или
void main(«string[] args») { instructions}
С# То же, что и выше; альтернативно, если только одно утверждение:

void foo(«parameters») => statement;

То же, что и выше; альтернативно, если это достаточно просто, чтобы быть выражением:

void foo(«parameters») => expression;

static void Main(«string[] args») method_body
Вместо этого может вернуться int.
(начиная с C# 7.1:) Может вернуться Task или Task<int>, и если да, то может быть async.
JavaScript function foo(«parameters») { instructions }
или
var foo = function («parameters») { instructions }
или
var foo = new Function ("«parameter»", ..., "«last parameter»" "instructions");
function foo(«parameters») { instructions ... return value; }
Идти func foo(«parameters») { instructions } func foo(«parameters») type { instructions ... return value } func main() { instructions }
Быстрый func foo(«parameters») { instructions } func foo(«parameters») -> type { instructions ... return value }
Общий Лисп (foo «parameters») (defun foo («parameters»)
  instructions)

или
(setf (symbol-function 'symbol)
  function)
(defun foo («parameters»)
  ...
  value
)
Схема (define (foo parameters) instructions)
или
(define foo (lambda (parameters) instructions))
(define (foo parameters) instructions... return_value)
или
(define foo (lambda (parameters) instructions... return_value))
ИСЛИСП (defun foo («parameters»)
  instructions)
(defun foo («parameters»)
  ...
  value
)
Паскаль foo«(parameters procedure foo«(parameters)»; «forward;»[a]
«label
  label declarations»
«const
  constant declarations»
«type
  type declarations»
«var
  variable declarations»
«local function declarations»

begin
  instructions
end;
function foo«(parameters)»: type; «forward;»[a]
«label
  label declarations»
«const
  constant declarations»
«type
  type declarations»
«var
  variable declarations»
«local function declarations»

begin
  instructions;
  foo := value
end;
program name;
«label
  label declarations»
«const
  constant declarations»
«type
  type declarations»
«var
  variable declarations»
«function declarations»

begin
  instructions
end.
Visual Basic Foo(«parameters») Sub Foo«(parameters
  instructions
End Sub
Function Foo«(parameters)»« As type»
  instructions
  Foo = value
End Function
Sub Main()
  instructions
End Sub
Визуальный Бейсик .NET То же, что и выше; альтернативно:

Function Foo«(parameters)»« As type»
  instructions
  Return value
End Function

The As пункт не требуется, если Option Strictвыключен. Вместо символа типа можно использовать As пункт.
Если элемент управления выходит из функции без явного указания возвращаемого значения, функция возвращает значение по умолчанию для возвращаемого типа.

Sub Main(««ByVal »args() As String»)
  instructions
End Sub
или
Function Main(««ByVal »args() As String») As Integer
  instructions
End Function
Содзё
Питон foo(«parameters») def foo(«parameters»):
Tab ↹instructions
def foo(«parameters»):
Tab ↹instructions
Tab ↹return value
Сленг foo(«parameters» «;qualifiers») define foo («parameters») { instructions } define foo («parameters») { instructions ... return value; } public define slsh_main () { instructions }
Фортран 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
Форт «parameters» FOO : FOO « stack effect comment: ( before -- ) »
  instructions
;
: FOO « stack effect comment: ( before -- after ) »
  instructions
;
PHP foo(«parameters») function foo(«parameters») { instructions } function foo(«parameters») { instructions ... return value; }
Перл foo(«parameters»)
или
&foo«(parameters
sub foo { «my (parameters) = @_;» instructions } sub foo { «my (parameters) = @_;» instructions... «return» value; }
Раку foo(«parameters»)
или
&foo«(parameters
«multi »sub foo(parameters) { instructions } «our «type» »«multi »sub foo(parameters) { instructions ... «return» value; }
Рубин foo«(parameters def foo«(parameters
  instructions
end
def foo«(parameters
  instructions
  «return» value
end
Ржавчина foo(«parameters») fn foo(«parameters») { instructions } fn foo(«parameters») -> type { instructions } fn main() { instructions }
Скала 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 };
или
function foo { «param(parametersinstructions }
function foo «(parameters)» { instructions ... return value };
или
function foo { «param(parametersinstructions ... return value }
Баш-оболочка foo «parameters» function foo {
  instructions
}

или
foo () {
  instructions
}
function foo {
  instructions
  return «exit_code»
}

или
foo () {
  instructions
  return «exit_code»
}
  • параметры
    • $n ( $1 , $2 , $3 , ...)
    • $@ (все параметры)
    • $# (количество параметров)
    • $0 (это имя функции)
OCaml foo parameters let «rec» foo parameters = instructions let «rec» foo parameters = instructions... return_value
Ф# [<EntryPoint>] let main args = instructions
Стандартный ML fun foo parameters = ( instructions ) fun foo parameters = ( instructions... return_value )
Хаскелл foo parameters = do
Tab ↹instructions
foo parameters = return_value
или
foo parameters = do
Tab ↹instructions
Tab ↹return value
«main :: IO ()»
main = do instructions
Эйфелева foo («parameters») foo («parameters»)
  require
     preconditions
  do
     instructions
  ensure
     postconditions
  end
foo («parameters»): type
  require
     preconditions
  do
     instructions
     Result := value
  ensure
     postconditions
  end
[б]
Кофескрипт foo() foo = -> foo = -> value
foo parameters foo = () -> foo = ( parameters ) -> value
КОБОЛ 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.
«FUNCTION» foo«(«parameters»)»
  • ^ Паскаль требует " forward;"для форвардных деклараций .
  • ^ b Eiffel позволяет указать корневой класс и функцию приложения.
  • ^c В Фортране параметры функции/подпрограммы называются аргументами (поскольку PARAMETERявляется ключевым словом языка); тот CALL Ключевое слово требуется для подпрограмм.
  • ^ d Вместо использования "foo"вместо этого можно использовать строковую переменную, содержащую то же значение.

Преобразования типов [ править ]

Где строка представляет собой десятичное число со знаком:

строка в целое число строка в длинное целое число строка с плавающей запятой целое число в строку с плавающей запятой в строку
Есть [1] Integer'Value (string_expression) Long_Integer'Value (string_expression) Float'Value (string_expression) Integer'Image (integer_expression) Float'Image (float_expression)
АЛГОЛ 68 с общими, а затем и специальными форматами С предварительным заявлением и ассоциацией: 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));
или
getf(proxy, ($dddd$, ivar));
getf(proxy, ($g$, livar));
или
getf(proxy, ($8d$, livar));
getf(proxy, ($g$, rvar));
или
getf(proxy, ($8d.4dE2d$, rvar));
putf(proxy, ($g$, ival));
или
putf(proxy, ($4d$, ival));
putf(proxy, ($g(width, places, exp)$, rval));
или
putf(proxy, ($8d.4dE2d$, rval));
АПЛ string_expression string_expression string_expression integer_expression float_expression
С ( С99 ) integer = atoi(string); long = atol(string); float = atof(string); sprintf(string, "%i", integer); sprintf(string, "%f", float);
Цель-C integer = [string intValue]; long = [string longLongValue]; float = [string doubleValue]; string = [NSString stringWithFormat:@"%i", integer]; string = [NSString stringWithFormat:@"%f", float];
С++ (СТЛ) «std::»istringstream(string) >> number; «std::»ostringstream o; o << number; string = o.str();
С++11 integer = «std::»stoi(string); long = «std::»stol(string); float = «std::»stof(string); double = «std::»stod(string); string = «std::»to_string(number);
С# 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)
Джава 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}`
Идти 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)
Ржавчина [д] 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()
Общий Лисп (setf integer (parse-integer string)) (setf float (read-from-string string)) (setf string (princ-to-string number))
Схема (define number (string->number string)) (define string (number->string number))
ИСЛИСП (setf integer (convert string <integer>)) (setf float (convert string <float>)) (setf string (convert number <string>))
Паскаль 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)
Визуальный Бейсик .NET
(можно использовать как синтаксис VB, указанный выше, так и методы .NET, показанные справа)
integer = Integer.Parse(string) long = Long.Parse(string) float = Single.Parse(string)
double = Double.Parse(string)
string = number.ToString()
Содзё integer = Val(string) long = Val(string) double = Val(string)
double = CDbl(string)
string = CStr(number)
или
string = Str(number)
Питон integer = int(string) long = long(string) float = float(string) string = str(number)
Сленг integer = atoi(string); long = atol(string); float = atof(string); string = string(number);
Фортран READ(string,format) number WRITE(string,format) number
PHP integer = intval(string);
или
integer = (int)string;
float = floatval(string);
float = (float)string;
string = "$number";
или
string = strval(number);
или
string = (string)number;
Перл [б] number = 0 + string; string = "number";
Раку number = +string; string = ~number;
Рубин integer = string.to_i
или
integer = Integer(string)
float = string.to_f
float = Float(string)
string = number.to_s
Скала integer = string.toInt long = string.toLong float = string.toFloatdouble = string.toDouble string = number.toString
Болтовня 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;
или
string = "number";
или
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
Ф# let integer = int string let integer = int64 string let float = float string let string = string number
Стандартный ML val integer = Int.fromString string val float = Real.fromString string val string = Int.toString integer val string = Real.toString float
Хаскелл ( GHC ) number = read string string = show number
КОБОЛ MOVE «FUNCTION» NUMVAL(string)[c] TO number MOVE number TO numeric-edited
  • ^a JavaScript использует только числа с плавающей запятой, поэтому есть некоторые технические особенности. [7]
  • ^b В Perl нет отдельных типов. Строки и числа взаимозаменяемы.
  • ^ с NUMVAL-C или NUMVAL-F может использоваться вместо NUMVAL.
  • ^ str::parse доступен для преобразования любого типа, который имеет реализацию std::str::FromStrчерта. Оба str::parse и FromStr::from_str вернуть Resultкоторый содержит указанный тип, если нет ошибки. Турборыба ( ::<_>) на str::parse можно опустить, если тип можно вывести из контекста.

Стандартный поток ввода/вывода [ править ]

читать из написать
стандартный ввод стандартный вывод stderr
Есть [1] Get (x) Put (x) Put (Standard_Error, x)
АЛГОЛ 68 readf(($format$, x));
или
getf(stand in, ($format$, x));
printf(($format$, x));
или
putf(stand out, ($format$, x));
putf(stand error, ($format$, x));[а]
АПЛ x← ⎕←x ⍞←x
С ( С99 ) scanf(format, &x);
или
fscanf(stdin, format, &x);[б]
printf(format, x);
или
fprintf(stdout, format, x);[с]
fprintf(stderr, format, x);[д]
Цель-C data = [[NSFileHandle fileHandleWithStandardInput] readDataToEndOfFile]; [[NSFileHandle fileHandleWithStandardOutput] writeData:data]; [[NSFileHandle fileHandleWithStandardError] writeData:data];
С++ «std::»cin >> x;
или
«std::»getline(«std::»cin, str);
«std::»cout << x; «std::»cerr << x;
или
«std::»clog << x;
С# x = Console.Read();
или
x = Console.ReadLine();
Console.Write(«format, »x);
или
Console.WriteLine(«format, »x);
Console.Error.Write(«format, »x);
или
Console.Error.WriteLine(«format, »x);
Д x = std.stdio.readln() std.stdio.write(x)
или
std.stdio.writeln(x)
или
std.stdio.writef(format, x)
или
std.stdio.writefln(format, x)
stderr.write(x)
или
stderr.writeln(x)
или
std.stdio.writef(stderr, format, x)
или
std.stdio.writefln(stderr, format, x)
Джава x = System.in.read();
или
x = new Scanner(System.in).nextInt();
или
x = new Scanner(System.in).nextLine();
System.out.print(x);
или
System.out.printf(format, x);
или
System.out.println(x);
System.err.print(x);
или
System.err.printf(format, x);
или
System.err.println(x);
Идти fmt.Scan(&x)
или
fmt.Scanf(format, &x)
или
x = bufio.NewReader(os.Stdin).ReadString('\n')
fmt.Println(x)
или
fmt.Printf(format, x)
fmt.Fprintln(os.Stderr, x)
или
fmt.Fprintf(os.Stderr, format, x)
Быстрый x = readLine() (2.х) print(x) (2.х)
println(x) (1.х)
JavaScript
Реализация веб-браузера
document.write(x)
JavaScript
Активные страницы сервера
Response.Write(x)
JavaScript
Хост сценариев Windows
x = WScript.StdIn.Read(chars)
или
x = WScript.StdIn.ReadLine()
WScript.Echo(x)
или
WScript.StdOut.Write(x)
или
WScript.StdOut.WriteLine(x)
WScript.StdErr.Write(x)
или
WScript.StdErr.WriteLine(x)
Общий Лисп (setf x (read-line)) (princ x)
или
(format t format x)
(princ x *error-output*)
или
(format *error-output* format x)
Схема ( Р 6 РС ) (define x (read-line)) (display x)
или
(format #t format x)
(display x (current-error-port))
или
(format (current-error-port) format x)
ИСЛИСП (setf x (read-line)) (format (standard-output) format x) (format (error-output) format x)
Паскаль read(x);
или
readln(x);
write(x);
или
writeln(x);
write(stderr, x);
или
writeln(stderr, x);
Visual Basic Input« promptx Print x
или
? x
Визуальный Бейсик .NET x = Console.Read()
или
x = Console.ReadLine()
Console.Write(«formatx)
или
Console.WriteLine(«format, »x)
Console.Error.Write(«format, »x)
или
Console.Error.WriteLine(«format, »x)
Содзё x = StandardInputStream.Read()
или
x = StandardInputStreame.ReadLine()
StandardOutputStream.Write(x)
или
StandardOutputStream.WriteLine(x)
StdErr.Write(x)
или
StdErr.WriteLine(x)
Питон 2.x x = raw_input(«prompt») print x
или
sys.stdout.write(x)
print >> sys.stderr, x
или
sys.stderr.write(x)
Питон 3.x x = input(«prompt») print(, end=""») print(, end=""», file=sys.stderr)
Сленг fgets (&x, stdin) fputs (x, stdout) fputs (x, stderr)
Фортран READ(*,format) variable names
или
READ(INPUT_UNIT,format) variable names[Это]
WRITE(*,format) expressions
или
WRITE(OUTPUT_UNIT,format) expressions[Это]
WRITE(ERROR_UNIT,format) expressions[Это]
Форт buffer length ACCEPT ( # chars read )
KEY ( char )
buffer length TYPE
char EMIT
PHP $x = fgets(STDIN);
или
$x = fscanf(STDIN, format);
print x;
или
echo x;
или
printf(format, x);
fprintf(STDERR, format, x);
Перл $x = <>;
или
$x = <STDIN>;
print x;
или
printf format, x;
print STDERR x;
или
printf STDERR format, x;
Раку $x = $*IN.get; x.print
или
x.say
x.note
или
$*ERR.print(x)
или
$*ERR.say(x)
Рубин x = gets puts x
или
printf(format, x)
$stderr.puts(x)
или
$stderr.printf(format, x)
Windows PowerShell $x = Read-Host«« -Prompt» text»;
или
$x = [Console]::Read();
или
$x = [Console]::ReadLine()
x;
или
Write-Output x;
или
echo x
Write-Error x
OCaml let x = read_int ()
или
let str = read_line ()
или
Scanf.scanf format (fun x ... -> ...)
print_int x
или
print_endline str
или
Printf.printf format x ...
prerr_int x
или
prerr_endline str
или
Printf.eprintf format x ...
Ф# let x = System.Console.ReadLine() printf format x ...
или
printfn format x ...
eprintf format x ...
или
eprintfn format x ...
Стандартный ML val str = TextIO.inputLIne TextIO.stdIn print str TextIO.output (TextIO.stdErr, str)
Хаскелл ( GHC ) x <- readLn
или
str <- getLine
print x
или
putStrLn str
hPrint stderr x
или
hPutStrLn stderr str
КОБОЛ ACCEPT x DISPLAY x
  • ^ a АЛГОЛ 68 дополнительно в качестве «неформатированных» процедур передачи : read, write, get, и put.
  • ^ б gets(x) и fgets(x, length, stdin)прочитать неформатированный текст из стандартного ввода. Использование get не рекомендуется.
  • ^ с puts(x) и fputs(x, stdout) записать неформатированный текст в стандартный вывод.
  • ^ д fputs(x, stderr) записывает неформатированный текст в stderr
  • INPUT_UNIT, OUTPUT_UNIT, ERROR_UNIT определены в Модуль ISO_FORTRAN_ENV . [15]

Чтение аргументов командной строки [ править ]

Значения аргументов Аргументы имеют значение Имя программы/имя сценария
Есть [1] Argument (n) Argument_Count Command_Name
С ( С99 ) argv[n] argc первый аргумент
Цель-C
С++
С# args[n] args.Length Assembly.GetEntryAssembly().Location;
Джава args.length
Д первый аргумент
JavaScript
хоста сценариев Windows Реализация
WScript.Arguments(n) WScript.Arguments.length WScript.ScriptName
или
WScript.ScriptFullName
Идти os.Args[n] len(os.Args) первый аргумент
Ржавчина [а] 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()
Быстрый Process.arguments[n] или
Process.unsafeArgv[n]
Process.arguments.count или
Process.argc
первый аргумент
Общий Лисп ? ? ?
Схема ( Р 6 РС ) (list-ref (command-line) n) (length (command-line)) первый аргумент
ИСЛИСП
Паскаль ParamStr(n) ParamCount первый аргумент
Visual Basic Command[б] App.Path
Визуальный Бейсик .NET CmdArgs(n) CmdArgs.Length [Assembly].GetEntryAssembly().Location
Содзё System.CommandLine (разбор строк) Application.ExecutableFile.Name
Питон sys.argv[n] len(sys.argv) первый аргумент
Сленг __argv[n] __argc первый аргумент
Фортран 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 первый аргумент
Баш-оболочка $n ($1, $2, $3, ...)
$@ (все аргументы)
$# $0
Перл $ARGV[n] scalar(@ARGV) $0
Раку @*ARGS[n] @*ARGS.elems $PROGRAM_NAME
Рубин ARGV[n] ARGV.size $0
Windows PowerShell $args[n] $args.Length $MyInvocation.MyCommand.Name
OCaml Sys.argv.(n) Array.length Sys.argv первый аргумент
Ф# args.[n] args.Length Assembly.GetEntryAssembly().Location
Стандартный ML List.nth (CommandLine.arguments (), n) length (CommandLine.arguments ()) CommandLine.name ()
Хаскелл ( GHC ) do { args <- System.getArgs; return length args !! n} do { args <- System.getArgs; return length args} System.getProgName
КОБОЛ [с]
  • В ржавчине, std::env::args и std::env::args_os возвращать итераторы, std::env::Args и std::env::ArgsOs соответственно. Args преобразует каждый аргумент в String и он паникует, если достигает аргумента, который невозможно преобразовать в UTF-8 . ArgsOs возвращает представление необработанных строк из операционной системы без потерь ( std::ffi::OsString), что может быть недействительным UTF-8.
  • ^b В Visual Basic аргументы командной строки не разделяются. Для их разделения требуется функция разделения. Split(string).
  • ^ c Стандарт COBOL не включает средств доступа к аргументам командной строки, но общие расширения компилятора для доступа к ним включают определение параметров для основной программы или использование ACCEPT заявления.

Выполнение команд [ править ]

Команда оболочки Выполнить программу Заменить текущую программу новой выполняемой программой
Есть [1] Не является частью языкового стандарта. Обычно это делается с помощью пакетов, предоставляемых компилятором, или путем взаимодействия с C или POSIX . [16]
С system("command"); execl(path, args);
или
execv(path, arglist);
С++
Цель-C [NSTask launchedTaskWithLaunchPath:(NSString *)path arguments:(NSArray *)arguments];
С# System.Diagnostics.Process.Start(path, argstring);
Ф#
Идти exec.Run(path, argv, envv, dir, exec.DevNull, exec.DevNull, exec.DevNull) os.Exec(path, argv, envv)
Visual Basic Interaction.Shell(command «, WindowStyle» «, isWaitOnReturn»)
Визуальный Бейсик .NET Microsoft.VisualBasic.Interaction.Shell(command «, WindowStyle» «, isWaitOnReturn») System.Diagnostics.Process.Start(path, argstring)
Содзё Shell.Execute(command «, Parameters») FolderItem.Launch(parameters, activate)
Д std.process.system("command"); std.process.execv(path, arglist);
Джава Runtime.exec(command);
или
new ProcessBuilder(command).start();
JavaScript
хоста сценариев Windows Реализация
WScript.CreateObject ("WScript.Shell").Run(command «, WindowStyle» «, isWaitOnReturn»); WshShell.Exec(command)
Общий Лисп (uiop:run-program command)
Схема (system command)
ИСЛИСП
Паскаль 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
или
Unix.execve prog args env
Стандартный ML OS.Process.system command Unix.execute (path, args) Posix.Process.exec (path, args)
Хаскелл ( GHC ) System.system command System.Process.runProcess path args ... Posix.Process.executeFile path True args ...
Перл system(command)
или
$output = `command`
или
$output = qx(command)
exec(path, args)
Рубин system(command)
или
output = `command`
exec(path, args)
PHP system(command)
или
$output = `command`
или
exec(command)
или
passthru(command)
Питон os.system(command)
или
subprocess.Popen(command)
subprocess.call(["program", "arg1", "arg2", ...]) os.execv(path, args)
Сленг system(command)
Фортран CALL EXECUTE_COMMAND_LINE (COMMAND «, WAIT» «, EXITSTAT» «, CMDSTAT» «, CMDMSG»)[а]
Windows PowerShell [Diagnostics.Process]::Start(command) «Invoke-Item »program arg1 arg2 ...
Баш-оболочка output=`command`
или
output=$(command)
program arg1 arg2 ...

^ Фортран 2008 или новее. [17]

Ссылки [ править ]

  1. ^ Перейти обратно: а б с д Это ж г час я дж к л м н О п Справочное руководство Ada – Языковые и стандартные библиотеки; ИСО/МЭК 8652:201x (Е), «Справочное руководство» (PDF) . Архивировано из оригинала (PDF) 27 апреля 2011 г. Проверено 19 июля 2013 г.
  2. ^ «Common Lisp HyperSpec (TM)» . lispworks.com . Проверено 30 января 2017 г.
  3. ^ «www.islisp.info: Спецификация» . islisp.info . Архивировано из оригинала 22 января 2016 года . Проверено 30 января 2017 г.
  4. ^ Перейти обратно: а б «selected_int_kind в Fortran Wiki» . fortranwiki.org . Проверено 30 января 2017 г.
  5. ^ «Эрланг — типы и характеристики функций» . erlang.org . Проверено 30 января 2017 г.
  6. ^ «Эрланг — Продвинутый» . erlang.org . Проверено 30 января 2017 г.
  7. ^ Перейти обратно: а б 8.5 Тип номера
  8. ^ Перейти обратно: а б «selected_real_kind в Fortran Wiki» . fortranwiki.org . Проверено 30 января 2017 г.
  9. ^ «Библиотека GNU C: комплексные числа» . gnu.org . Проверено 30 января 2017 г.
  10. ^ «Грамматика вб» . Спецификация языка Visual Basic . 17.06.2016. Архивировано из оригинала 29 августа 2019 г. Проверено 29 августа 2019 г.
  11. ^ «для... из» . сайт mozilla.org . Проверено 30 января 2017 г.
  12. ^ «Попробуй-поймай для VB» . гугл.com . Архивировано из оригинала 16 апреля 2016 года . Проверено 30 января 2017 г.
  13. ^ Клабник, Стив; Николс, Кэрол. "Обработка ошибок" . Язык программирования Rust .
  14. ^ «Простое разложение – Розеттский код» . Rosettacode.org . Проверено 30 января 2017 г.
  15. ^ «iso_fortran_env в Fortran Wiki» . fortranwiki.org . Проверено 30 января 2017 г.
  16. ^ «Выполнить системную команду – Rosetta Code» . Rosettacode.org . Проверено 30 января 2017 г.
  17. ^ «EXECUTE_COMMAND_LINE — Компилятор GNU Fortran» . gnu.org . Проверено 30 января 2017 г.
Arc.Ask3.Ru: конец оригинального документа.
Arc.Ask3.Ru
Номер скриншота №: 7E51D669B5BC1E225F14C2EF3F7DD33C__1717529700
URL1:https://en.wikipedia.org/wiki/Comparison_of_programming_languages_(basic_instructions)
Заголовок, (Title) документа по адресу, URL1:
Comparison of programming languages (basic instructions) - Wikipedia
Данный printscreen веб страницы (снимок веб страницы, скриншот веб страницы), визуально-программная копия документа расположенного по адресу URL1 и сохраненная в файл, имеет: квалифицированную, усовершенствованную (подтверждены: метки времени, валидность сертификата), открепленную ЭЦП (приложена к данному файлу), что может быть использовано для подтверждения содержания и факта существования документа в этот момент времени. Права на данный скриншот принадлежат администрации Ask3.ru, использование в качестве доказательства только с письменного разрешения правообладателя скриншота. Администрация Ask3.ru не несет ответственности за информацию размещенную на данном скриншоте. Права на прочие зарегистрированные элементы любого права, изображенные на снимках принадлежат их владельцам. Качество перевода предоставляется как есть, любые претензии не могут быть предъявлены. Если вы не согласны с любым пунктом перечисленным выше, немедленно покиньте данный сайт. В случае нарушения любого пункта перечисленного выше, штраф 55! (Пятьдесят пять факториал, денежную единицу можете выбрать самостоятельно, выплаичвается товарами в течение 7 дней с момента нарушения.)