Типы

Урок 11. Типы в PascalABC.NET. Создание своего типа.

Приветствуем тебя, юный (или не очень юный) читатель нашего сайта! Сегодня мы с вами поговорим про типы в PascalABC.NET: числовые, символьные и логические. Они немного отличаются от стандартных типов Turbo Pascal.

Давайте вспомним какими могут быть величины? Об этом говорилось в отдельной статье. Сейчас мы быстренько все впомним. Любая величина может быть трех типов: числовой, символьной и логическй. Раньше мы использовали всего несколько типов (integer, real, boolean ), но пришло время расширить знания.

Типы

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

Важно! Все диапазоны и типы действительны только для PascalABC.NET, во Free Pascal и Turbo Pascal у этих типов будут другие значения. Например, в  PascalABC.NET тип integer имеет диапазон от -2147483648 до 2147483647, а в Turbo Pascal  у этого типа диапазон  от -32768 до 32767.

Числовые типы

Принято разделять числовые типы на две большие подгруппы: целые и вещественные.

Целые типы

Тип  Размер в байтах Диапазон значений
shortint 1 -128..127
smallint 2 -32768..32767
integer, longint 4 -2147483648..2147483647
int64 8 -9223372036854775808..9223372036854775807
byte 1 0..250
word 2 0..65535
longword, cardinal 4 0..4294967295
uint64 8 0..18446744073709551615

Вещественные типы

Тип  Размер в байтах Диапазон значений Количесвто значащих цифр
real 8 -1.8∙10308 .. 1.8∙10308 15-16
double 8 -1.8∙10308 .. 1.8∙10308 15-16
single 4 -3.4∙1038 .. 3.4∙1038 7-8

Для удобства в Паскале заведены специальные константы, которые возвращают на свое место минимальное или максимальное значение разных типов. Ниже вы можете посмотреть таблицу, в которую занесены все константы.

Константа(1) Константа(2) Значение
MaxShortInt shortint.MaxValue Максимальное значение типа shortint
MaxByte byte.MaxValue Максимальное значение типа byte
MaxSmallInt smallint.MaxValue Максимальное значение типа smallint
MaxWord word.MaxValue Максимальное значение типа word
MaxInt integer.MaxValue Максимальное значение типа integer
MaxLongWord longword.MaxValue Максимальное значение типа longword
MaxInt64 int64.MaxValue Максимальное значение типа int64
MaxUint64 uint64.MaxValue Максимальное значение типа uint64
MaxDouble double.MaxValue Максимальное значение типа double
MinDouble real.Epsilon Минимальное значение типа double
MaxReal real.MaxValue Максимальное значение типа real
MinReal real.Epsilon Минимальное значение типа real
MaxSingle single.MaxValue Максимальное значение типа single
MinSingle single.Epsilon Минимальное значение типа single

Логический тип

В PascalABC.NET  только один логический тип — boolean. Про него была написана целая статья. Тип Boolean принимает значение true или false, и его размер — 1 байт.

Символьный тип и строки

Символьный тип

Символьный тип char занимает 2 байта и хранит Unicode-символ.

Чтобы не писать отдельную  статью про символьный тип, вкратце расскажу про него здесь. В   PascalABC.NET помимо стандартных функций chr  и ord, добавлены новые функции — ChrUnicode и OrdUnicode.

Chr(n) — функция, возвращающая символ с кодом n в кодировке Windows;
Ord(с) — функция, возвращающая значение типа byte, представляющее собой код символа c в кодировке Windows.

ChrUnicode(w) — возвращает символ с кодом w в кодировке Unicode;
OrdUnicode(с) — возвращает значение типа word, представляющее собой код символа c в кодировке Unicode.

Давайте поэкспериментируем, составим вот такую небольшую программку.

program Chr_Ord_Example;

begin
  writeln(ChrUnicode(30000));
  writeln(OrdUnicode('*'));
  writeln(Chr(42));
  writeln(Ord('*'));
end.

Этой программой я хочу проверить накладываются ли друг на друга кодировка Windows  и Unicode. Ниже, на скриншоте вы можете посмотреть результат работы программы.

Символьный тип в Паскаль
Накладываются. Просто Unicode длиннее, чем кодировка Windows.

Строковой тип

Строки имеют тип string, состоят из набора последовательно расположенных символов char и используются для представления текста.

Строки могут иметь произвольную длину.  Строки изменяемы.

Наверное, сейчас вы сомневаетесь в том, что в PascalABC.NET строки могут быть произвольной длины. Давайте проверим это с помощью небольшой программы.

program String_Example;

label m1;
begin
  var s: string; {Так как мы с вами работает в PascalABC.NET, то данная конструкция здесь не является ошибкой.}
  var n := 0; 
  s := 'HelluuHelluuuuuuuulluuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo!Helluuuuuuuuuuuuuuuuuu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uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo!uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo!uuuuuuuuuuuuuuuuuuuuuuo!HelluuHelluuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo!uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo!!uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo!uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo!HelluuHelluuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo!uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo!uuuuuuuuuuuuuuuuuuuuuuo!HelluuHelluuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuoHelluuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo!HelluuHelluuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo!uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo!uuuuuuuuuuuuuuuuuuuuuuo!HelluuHelluuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo!uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo!!uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo!';
  writeln(Length(s)); {Функция length() возвращает длину строки.}
  m1: {ставим метку}
  s := s + s; {В программировании операция сложения, выполненная со строками, называется конкатенацией}
  Inc(n);
  if n < 11 then goto m1;
  writeln(Length(s));
end.

Строковой тип

Кроме того, в PascalABC.NET реализованы размерные строки. Для их описания используется тип string[n], где n — константа целого типа, указывающая длину строки.

Перечислимый и диапазонный типы

Перечислимый тип

Перечислимый тип определяется упорядоченным набором идентификаторов. Чтобы объявить  новый тип, используется специальное слово — type. Его необходимо ставить перед var.

type
  typeName = (value1, value2, ..., valueN);

Значения перечислимого типа занимают 4 байта. Каждое значение value представляет собой константу типа typeName, попадающую в текущее пространство имен.

Например:

type
  Month = (January, February, March, April, May, June, July, August, September, October, November, December);

К константе перечислимого типа можно обращаться непосредственно по имени, а можно использовать запись typeName.value, в которой имя константы уточняется именем перечислимого типа, к которому она принадлежит:

var
  a, b: month;

begin
  a := February;
  b := Month.August;
end.

Для значений перечислимого типа можно использовать функции Ord, Pred и Succ, а также процедуры Inc и Dec (Подробнее про эти функции и процедуры). Функция Ord возвращает порядковый номер значения в списке констант соответствующего перечислимого типа, нумерация при этом начинается с нуля.

program type_example;

type
  Month = (January, February, March, April, May, June, July, August, September, October, November, December);

var
  a, b: month;

begin
  a := February;
  b := Month.August;
  writeln(a,' , ',b);
  Inc(a);
  b := pred(b);
  writeln(a,' , ',b);
  writeln(Ord(a),' , ',Ord(b));
end.
Перечисляемый тип
Результат работы программы

Диапазонный тип

Диапазонный тип представляет собой подмножество значений целого, символьного или перечислимого типа и описывается в виде a..b, где a — нижняя, b — верхняя граница интервального типа, a<b.

Пример.

program type_example;

type
  Month = (January, February, March, April, May, June, July, August, September, October, November, December);

var
  a : January..May;
  b : 1..10;
  c : 'a'..'z';

begin
  a := March;
  b := 2;
  c := 'b';
  b := pred(b);
  writeln(a,' , ',b,' , ', c);
end.
Диапазонный тип
Результат работы программы

Тип, на основе которого строится диапазонный тип, называется базовым для этого диапазонного типа. Значения диапазонного типа занимают в памяти столько же, сколько и значения соответствующего базового типа.

На сегодня все! Урок получился объемным, но, надеюсь, понятным. Если же у вас возникли вопросы, напишите нам.

  • Тоа

    Суперский сайт.
    С 6 класса мечтал стать программистом
    И выучить программные языки.
    Этот сайт лучший ,все понятно.