Basic Pascal Tutorial/Chapter 5/Enumerated types

From Lazarus wiki
Revision as of 14:24, 2 November 2017 by Tudi x (talk | contribs)
Jump to navigationJump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

български (bg) English (en) français (fr) 日本語 (ja) 中文(中国大陆)‎ (zh_CN)

 ◄   ▲   ► 

5A - Enumerated Types (author: Tao Yue, state: unchanged)

You can declare your own ordinal data types. You do this in the type section of your program:

type
 datatypeidentifier = typespecification;

One way to do it is by creating an enumerated type. An enumerated type specification has the syntax:

(identifier1, identifier2, ... identifiern)

For example, if you wanted to declare the months of the year, you would do a type:

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

You can then declare a variable:

var
  Month : MonthType;

You can assign any enumerated value to the variable:

Month := January;

All the ordinal functions are valid on the enumerated type. ord(January) = 0, and ord(December) = 11. Or if the variable should go to next month a call to Succ(variable) can be made. Consider verifying with variable < High(MonthType) that there is a next month.

A few restrictions apply, though: enumerated types are internal to a program -- they can neither be read from nor written to a text file. You must read data in and convert it to an enumerated type. Also, the identifier used in the type (such as January) cannot be used in another type.

One purpose of an enumerated type is to allow you, the programmer, to refer to meaningful names for data. In addition, enumerated types allow functions and procedures to be assured of a valid parameter, since only variables of the enumerated type can be passed in and the variable can only have one of the several enumerated values.

Write and Writeln can be used to print a string representing the current value in an enumerated type variable. WriteStr(string-var,enum-var) can be used to place a string representation of the enum value into a string.

 ◄   ▲   ►