Home Tutorial Win32 API Reference Projects

Chapter 3 - The simple Modula-2 data types.


The material in this chapter is extremely important to you as you strive to become a good Modula-2 programmer, but you may also find it to be somewhat tedious because it contains so many facts. This material is needed in order to develop the topics in the next few chapters, but all of the details are not necessarily required. For that reason, you may wish to go through it rather rapidly picking up the high points and come back to this chapter for the details later when they will be much more meaningful. Do not completely pass over this material at this time or the next few chapters will be meaningless unless you are already highly experienced in other programming languages.

A program with variables

Load and display the program named INTVAR.MOD for our first program with some variables in it. This program begins in the usual way since it has a MODULE header and the IMPORT list. Next we come to a new reserved word, VAR. This word is used to indicate to the compiler that we wish to define one or more variables. In Modula-2, there is a rule that says you can use nothing until it is defined. If we wish to use a variable in the program, we must first define that it will exist, and what kind of a variable it is. After that, it can be used in the program to do what needs to be done.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
MODULE IntVar;

FROM Terminal2 IMPORT WriteLn, WriteString, WriteInt;

VAR Count : INTEGER;  (* The sum of two variables *)
    x,y   : INTEGER;  (* The two variables to add *)

BEGIN

   x := 12;
   y := 13;
   Count := x + y;

          (* Assignments complete, now display the results *)

   WriteString("The value of x  =");
   WriteInt(x,3);
   WriteLn;
   WriteString("The value of y  =");
   WriteInt(y,4);
   WriteLn;
   WriteString("The sum of them =");
   WriteInt(Count,6);
   WriteLn;

   x := 0FFH;   (* This is the way to assign a hexadecimal number *)
   y := 177B;   (* This is the way to assign an octal number      *)

END IntVar.

Following the reserved word VAR, we have the variable named "Count" defined. The reserved word INTEGER following the colon states that the variable "Count" will be of type INTEGER. This means that it can store any whole number between -32768 to 32767 (on 16-bit compilers). Don't worry too much about this yet, the next program will completely define what an INTEGER type variable is. It is important to recognize that after we have defined the variable "Count", it still doesn't have a value stored in it, that will come later.

The next line (line 6) has two more variables defined, namely "x", and "y". They are also INTEGER type variables and do not have a value stored in them yet. You can think of the three variables as three empty boxes, each capable of storing a number but with no number in them yet. It would be perfectly permissible to put all three variables on one line, or to have separated them such that each was on a separate line. At this point, the program doesn't know that there is any difference between them, because there isn't any. The fact that one will contain the sum of the other two has no meaning yet, the comments are only for us, not the computer.

Using variables in a program

Now we will go to the program itself. Line 10 sets the variable "x" equal to 12, in effect putting the number 12 in the box mentioned earlier. The sign := is the Modula-2 symbol for assignment. It is most meaningful to read the symbol "gets the value of" since it is not really stating a mathematical equality but is saying in effect, "assign the value of this to the variable at the left." The entire line can be read as "x gets the value of 12." There is now a value assigned to the variable "x" declared in the header. The next statement assigns the value of 13 to the variable "y". Finally the value of the data stored in the variable "x" is added to the value of the data stored in the variable "y", and the sum is stored in the variable "Count". We have therefore done our first calculations in Modula-2 but we will do many more before this tutorial is completed.

Notice that each statement is terminated with a semicolon, a Modula-2 requirement.

The three variables are then displayed on the monitor with appropriate prose to identify them. The only new statement here is the "WriteInt" procedure that needs a little explanation. This procedure is used to output an INTEGER type variable to the monitor or whatever device is being used. By definition, it contains two quantities within the parentheses, the variable name and the number of columns it should fill. If there are not enough columns to output the data, more will be used so that no digits will be truncated. If all are not needed, leading blanks will be output. If the variable "x" had the value of 1234 when we came to program line 17, all four digits would be output in spite of the request for three. Since "x" has the value of 12, only two columns will be used and one leading blank will be output. In like manner, "y" is allotted 4 columns and "Count" is to be output in 6 columns.

Lines 26 & 27 of the program assign new values to two of the variables. The variable "x" is assigned the value of FF hexadecimal which is 256 decimal, and "y" is assigned the value of 177 octal which is 127 decimal. This is only done as an illustration to you of how it is done. If you don't understand these two numbering systems, simply ignore this until you have a need for it.

Compile and run this program to see if it does what you expect it to do. The important thing to notice in this program is the variable definition in the definition part of the module and the variable assignment in the program part. It should be obvious, but it would be well to mention that the definition part of the module extends from the module name to the reserved word "BEGIN" and is where all definitions are put. Likewise, the program part of the module includes all statements from the "BEGIN" to the "END".

Simple variable types

Modula-2 has several predefined data types that you can use in your programs. You also have the ability to define any number of complex types built up from the simple types but we will not discuss this until we get to chapter 6 and beyond. The simple types are INTEGER, CARDINAL, REAL, BOOLEAN, and CHAR. Each has its own purpose and its own peculiarities and we will cover each type one at a time.

The simple variable - INTEGER

Load and display the program named INTMATH.MOD for an example of INTEGER math. In the declaration part of the program (the part prior to the BEGIN) we have 7 INTEGER type variables defined for use in the program. We will use them to illustrate INTEGER arithmetic.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
MODULE IntMath;

FROM Terminal2 IMPORT WriteLn, WriteString, WriteInt;

VAR IntSum, IntDif, IntMul, IntDiv, IntRem : INTEGER;
    A, B                                   : INTEGER;

BEGIN
   A := 9;             (* Simple assignment                  *)
   B := A + 4;         (* Addition                           *)
   IntSum := A + B;    (* Addition                           *)
   IntDif := A - B;    (* Subtraction                        *)
   IntMul := A * B;    (* Multiplication                     *)
   IntDiv := B DIV A;  (* Integer division, the result is a
                          truncated integer number.          *)
   IntRem := B MOD A;  (* d is the remainder of the integer
                          division.                          *)
   A := (A + B) DIV (3*B + 7);  (* Composite math statement  *)

   WriteString("The integer values are ");
   WriteInt(IntSum,6);
   WriteInt(IntDif,6);
   WriteInt(IntMul,6);
   WriteInt(IntDiv,6);
   WriteInt(IntRem,6);
   WriteLn;

   INC(A);       (* This increments the value of A   *)
   DEC(A);       (* This decrements the value of A   *)
   INC(A,3);     (* This adds 3 to the value of A    *)
   DEC(A,7);     (* This reduces the value of A by 7 *)
   INC(A,B*2+4); (* A composite incrementing amount  *)

   A := MIN(INTEGER);  (* This produces the smallest INTEGER *)
   B := MAX(INTEGER);  (* This produces the largest INTEGER  *)

END IntMath.

An INTEGER variable, by definition, can store any whole number between -32768 and 32767 (on 16-bit compilers; on 32-bit compilers an INTEGER can store whole number from -2,147,483,648 to 2,147,483,647). An attempt to store any other value in an INTEGER type variable should produce an error by your compiler but it may produce some other result. Some compilers may store a -32769, which is one count too low, as a 32767 which is at the top end of the range. This is due to the two's complement arithmetic that you don't need to understand at this point. It will be left to you to determine what your compiler does in such a case.

The first line in the program is nothing new to you, it simply assigns the value 9 to variable "A". The second line adds 4 to the value stored in the variable "A" and the result, 13, is stored in the variable "B". Next the values stored in the variables "A" and "B" are added together and the sum, which is 9 + 13, is stored in the variable "IntSum". Continuing in the same manner, the difference and the product are calculated and stored. When we come to INTEGER division (line 14), we are breaking new ground because the result is truncated to the largest whole number resulting from the division. Thus 13 DIV 9 results in 1 because the remainder is simply dropped. The next construct, B MOD A results in the remainder of the division, in this case 4. You will find these operations very useful as you progress as a Modula-2 programmer.

The intent of the next line (line 18) is to illustrate that you can do several math operations in a statement if you are careful to put the parentheses in the proper places. There are definite rules about operator precedence but I recommend that you use lots of parentheses to remove all doubt as to what the results will be.

The results of the operations are displayed in 6 columns and we move on to several new operations. The first new operation is the "INC" which is short for "increment". This simply increments the variable contained within the parentheses and if a second argument is given, the variable is incremented by the value of that variable. In like manner the "DEC" procedure decrements the variable in the parentheses by one unless a second argument is given in which case the variable is decremented by the value of that variable.

It may not be clear at this point, but the second variable itself may be another variable name or even a composite of several as long as it results in an INTEGER type variable. This is illustrated in the program.

Finally, we come to the last two procedures in this program, the "MIN" and the "MAX". These two procedures will return the value of the smallest possible INTEGER, -32768 and the largest possible INTEGER, 32767. These are the values returned when using 16-bit compiler.

The simple variable - CARDINAL

Load and display the file named CARDMATH.MOD for an example of CARDINAL mathematics and output. In this file, 7 variables are defined as CARDINAL and one more as INTEGER. A CARDINAL variable can store any whole number from 0 to 65535 in a 16-bit microcomputer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
MODULE CardMath;

FROM Terminal2 IMPORT WriteLn, WriteString, WriteCard;

VAR CardSum, CardDif, CardMul, CardDiv : CARDINAL;
    A, B, CardRem                      : CARDINAL;
    IntVar                             : INTEGER;

BEGIN
   A := 9;              (* Simple assignment                  *)
   B := A + 4;          (* Addition                           *)
   CardSum := A + B;    (* Addition                           *)
   CardDif := B - A;    (* Subtraction                        *)
   CardMul := A * B;    (* Multiplication                     *)
   CardDiv := B DIV A;  (* Integer division, the result is a
                          truncated integer number.          *)
   CardRem := B MOD A;  (* d is the remainder of the integer
                          division.                          *)
   A := (A + B) DIV (3*B + 7);  (* Composite math statement  *)

   WriteString("The cardinal values are ");
   WriteCard(CardSum,6);
   WriteCard(CardDif,6);
   WriteCard(CardMul,6);
   WriteCard(CardDiv,6);
   WriteCard(CardRem,6);
   WriteLn;

   IntVar := A;       (* INTEGER and CARDINAL are assignment  *)
   B := IntVar + 27;  (* compatible, but cannot be mixed in   *)
                      (* any expression.                      *)

   A := 125;          (* CARDINAL assignment                  *)
   B := A - 112;      (* CARDINAL math                        *)
(* B := 125 + (-112);    Illegal CARDINAL Math - see text     *)

   IntVar := 125 + (-112);       (* INTEGER math, OK here     *)

   INC(A);      (* This increments the value of A       *)
   DEC(A);      (* This decrements the value of A       *)
   INC(A,4);    (* This adds 4 to the value of A        *)
   DEC(A,6);    (* THis subtracts 6 from the value of A *)

   A := MIN(CARDINAL);  (* This produces the minimum CARDINAL *)
   B := MAX(CARDINAL);  (* This produces the maximum CARDINAL *)

END CardMath.

The first few lines are the same as the last program so very little needs to be said about them except for the subtraction example. In this case, the result of the subtraction would be negative if it were carried out as in the last program so "A" is subtracted from "B". It is an error to attempt to store a negative number in a CARDINAL type variable. For that reason, a CARDINAL should not be used if there is any chance that it will go negative. Programming experience will be the best teacher when it comes to deciding what variables to use in each situation.

In this program the variables are once again displayed, but now the procedure named "WriteCard" is used for output because the variables to output are CARDINAL.

The next two statements indicate that INTEGER and CARDINAL variables are "assignment compatible" meaning that they can be assigned to each other with the := operator. They cannot however, be mixed in calculations. Constants in an expression are assumed to be of the same type as the variables in the expression and they must agree. For that reason, the expression in line 35 is invalid because (-112) is required to be a CARDINAL constant but it is negative and therefore not CARDINAL. In the prior line it is permissible to subtract 112 from the value of "A" as long as the result is still positive. As an exercise, change line 33 such that a number less than 112 is assigned to "A". The program will compile without error but when you run it, you should get a runtime error because the CARDINAL assignment is out of range. Notice that the constant value of -112 is allright for use an an INTEGER variable.

The remaining statements in the program are the same as the last program so additional explanation is unneeded. It would be good to point out that in the case of CARDINAL, the "MIN" and "MAX" procedures will return values of 0 and 65535 when using a 16-bit compiler.

The simple variable - REAL

Load and display the program named REALMATHS.MOD for a demonstration of the data type REAL. The definition part of this program is similar to the last with some additions to the IMPORT list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
MODULE RealMaths;

FROM Terminal2 IMPORT WriteString, WriteLn, WriteReal;

VAR Sum, Diff, Product, Div : REAL;
    A, B    : REAL;
    Inumber : INTEGER;
    Cnumber : CARDINAL;

BEGIN
   A   := 3.234;                    (* Assigns a value          *)
   B   := A + 1.0123;               (* Add a constant           *)
   Sum := A + B;                    (* Add two variables        *)
   Product := A * B;                (* Multiplication           *)
   Div  := A / B;                   (* Division                 *)
   Diff := A - B;                   (* Subtraction              *)
   A := (A + B)/(12.345 * A - B);   (* Multiple math expression *)

   WriteString("The REAL values are");
   WriteReal(Sum,12);
   WriteString("  ");
   WriteReal(Diff,12);
   WriteString("  ");
   WriteReal(Product,12);
   WriteString("  ");
   WriteReal(Div,12);
   WriteLn;

         (* Conversion between data types - illustration  *)

   Inumber := 15;          (* This is an INTEGER              *)
   Cnumber := 333;         (* This is a CARDINAL              *)
   A := FLOAT(Inumber);    (* INTEGER to REAL                 *)
   B := FLOAT(Cnumber);    (* CARDINAL to REAL                *)
   Inumber := TRUNC(Sum);  (* REAL to INTEGER                 *)
   Cnumber := TRUNC(Sum);  (* REAL to CARDINAL                *)

   A := MIN(REAL);   (* This produces the smallest REAL *)
   A := MAX(REAL);   (* This produces the largest REAL  *)

END RealMaths.

Several REAL variables and one each of the INTEGER and CARDINAL types are defined for use in the program. The REAL type variable can contain numbers in a wide range and with fractional parts included. The exact range, and the accuracy will vary widely depending on your implementation. It will be up to you to check your reference manual for the limits on your computer and compiler. A REAL type number is defined as one with a decimal point. The mathematics are the same as with the other two except that the division symbol is the slash (/). There is no "MOD" for REAL type numbers because there is theoretically no remainder, since a fractional part is computed as part of the calculation.

The four results are displayed on the monitor with 12 columns allowed for each result and two extra blanks displayed between each number. Unfortunately, we have no control over how many digits will be displayed following the decimal point. This would be nice for outputting data in a financial model where we would like to have two digits following the decimal point.

Conversion between data types

Beginning in line 31, we assign the INTEGER and CARDINAL variables some values and next convert the values to type REAL by using the procedure "FLOAT". We then convert the variable "Sum" to INTEGER and CARDINAL by use of the procedure "TRUNC". The fractional part, if any, will simply be discarded. These procedures will be very useful in many of your programs.

The last two lines return the value of the largest possible REAL number and the smallest REAL number for your implementation.

Compile and run this program.

The simple variable - BOOLEAN

Load and display the file named BOOLMATH.MOD on your monitor for an example of BOOLEAN variables. A BOOLEAN variable can only have one of two possible values, TRUE or FALSE. These variables cannot be printed directly but can be used to control other print statements to print out a representation of their value. We will see how later.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
MODULE BoolMath;

VAR IsIt, WillIt, What : BOOLEAN;
    A, B, C            : INTEGER;

BEGIN

   A := 22;        (* Assign some values to work with *)
   B := 12;
   C := -12;

   IsIt := A = 22;     (* TRUE    - equal to                    *)
   IsIt := A = 23;     (* FALSE   - equal to                    *)
   WillIt := A > B;    (* TRUE    - greater than                *)
   WillIt := A < B;    (* FALSE   - less than                   *)
   What := WillIt;     (* FALSE   - assignment                  *)
   IsIt := B <= 12;    (* TRUE    - less than or equal          *)
   IsIt := B >= 4;     (* TRUE    - greater than or equal       *)
   IsIt := A # B;      (* FALSE   - not equal                   *)
   IsIt := A <> B;     (* TRUE    - not equal                   *)

   IsIt := TRUE;
   What := FALSE;
   WillIt := IsIt AND What;      (* FALSE because What is FALSE *)
   WillIt := IsIt AND NOT What;  (* TRUE                        *)
   WillIt := IsIt OR What;       (* TRUE because one is TRUE    *)
   WillIt := NOT IsIt OR What;   (* FALSE                       *)
   IsIt := (A = B) OR (B = C) OR (A = 22);
   IsIt := ((A < B) AND (B < C)) OR NOT (B > C);

   (* We have not studied a way to print out representations of *)
   (* BOOLEAN variables so it will have to wait.                *)

END BoolMath.

We define 3 BOOLEAN variables and 3 INTEGER variables and assign values to the 3 INTEGER variables in the program for use in these illustrations. In line 12 the BOOLEAN expression "A = 22" is TRUE, therefore the BOOLEAN variable "IsIt" is assigned the value TRUE. The variable "IsIt" could be used later in the program to make a decision, by a yet undefined method, to do something or bypass it. In like manner, the next statement assigns "IsIt" the value FALSE because A is not equal to 23. The remainder of the allowed BOOLEAN expressions are defined in the next few lines and are left for your inspection and study.

Beginning in line 24, composite BOOLEAN expressions are illustrated. As many BOOLEAN expressions as desired can be combined with AND and OR operators. If two or more BOOLEAN expressions are combined with the AND, the result is TRUE if all expressions are TRUE. If two or more BOOLEAN expressions are combined with the OR, the result is true if any of them are TRUE. The NOT operator inverts the sense of what it modifies, it turns a TRUE to FALSE and vice-versa. Finally a couple of composite BOOLEAN expressions are given for illustration of the amount of complexity that is allowed, although there is no real limit as to how far you can go with the complexity. Good programming practice would dictate that you keep it simple and understandable.

Two rules for boolean evaluation

First it is important that you use the same type of variables within a BOOLEAN expression. REAL's can be compared to REAL's and INTEGER's to INTEGERs, but REAL's cannot be compared to INTEGER's. CARDINAL and CHAR types can also be compared to their own types, but none of the four can be compared directly to each other.

Secondly, Modula-2 uses a shortcut evaluation technique for BOOLEAN evaluation. Evaluation proceeds from left to right and if it finds a result which will positively determine the outcome, evaluation stops. For example, if it is evaluating a string of 5 comparisons all combined with an AND, and it finds that the second term is FALSE, evaluation stops there. Since all terms must be TRUE for the result to be TRUE, it makes no difference what values the last three are, the result will be FALSE because of the second term. On the other hand, when evaluating a string of 5 comparisons all combined with an OR, and it is found that the second term is TRUE, then the total expression must be TRUE and evaluation at that point can and will stop.

For example consider the following two expressions:

  ok := (C=5/A) OR (A=0)   and
  ok := (A=0) OR (C=5/A)

Since boolean expressions are evaluated from left to right then, if A equals 0, the first expression will result in a compiler warning or run-time error (Division by zero) when evaluating (5/A). On the other hand, the outcome of the second expression is well established after evaluation of the first part of the expression (A=0) and the varialbe ok at that point must be TRUE. Therefore the last part of the expression (C=5/A) will not be evaluated when A equals 0, and an error will be avoided.

This is a very important feature of Modula-2

The simple variable - CHAR

Load and display the program named CHARDEMO.MOD for an illustration of the last simple variable type, CHAR. Text data is stored in a computer in a format utilizing the CHAR data type. Although there are exceptions, such as when text is stored in some form of a packed mode, this is nearly always true.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
MODULE CharDemo;

FROM Terminal2 IMPORT WriteLn, WriteChar, WriteString;

VAR Char1, Char2, Dog3, Cat4 : CHAR;
    Index                    : INTEGER;

BEGIN

   Char1 := 'A';                     (* This is a capitol A      *)
   Char2 := "T";                     (* This is a capitol T      *)
   Index := ORD(Char1) + 2;          (* The numerical value of A
                                        plus 2 = the value of C  *)
   Dog3 := CHR(Index);               (* The letter C             *)
   Cat4 := '"';                      (* The quotation mark       *)

   WriteString("The characters can spell ");
   WriteChar(Cat4);
   WriteChar(Dog3);
   WriteChar(Char1);
   WriteChar(Char2);
   Char1 := "S";                     (* Change to the letter S   *)
   WriteChar(Char1);
   WriteChar(Cat4);
   WriteLn;

   Char1 := 65C;                       (* This sets Char1 to 'A' *)
   Char1 := 'a';                       (* This sets Char1 to 'a' *)
   Char2 := CAP(Char1);                (* This sets Char2 to 'A' *)

END CharDemo.

Although there are many different ways to store text, ASCII is most commonly used in microcomputers, so we will limit our discussion to ASCII. ASCII merely refers to the way the characters of the alphabet and all other characters are represented in the computer. The ASCII standard defines that the value of 65 will be the letter 'A', 66 will be the letter 'B', etc. If everyone uses the same standard, transfer of data from one computer to another is greatly simplified.

The program named CHARDEMO has the usual header with 4 CHAR type variables defined for use in the program. An INTEGER is also defined. In the program itself, we begin by assigning 2 of the variables some CHAR data. Since a CHAR variable is capable of storing one letter, numeral, or special character, each variable is assigned one letter. The single or double quotes are used as an indication to the compiler that you intend for it to use the letter as a CHAR type variable rather than as another variable name. Of course if you wanted to use "A" as a variable name, you would have to define it in the definition part of the module.

Two special CHAR procedures

The next instruction (line 12) gets the ordinal value of the letter "A", adds two to it, and assigns that value to the variable "Index", which must be an INTEGER (although it could have been defined as a CARDINAL). Refer to the documentation that came with your computer and you will find an ASCII table that will define the letter "A" as 65. Finally, the CHAR type variable "Dog3" is assigned the character value of "Index". Your ASCII table should define 67 as the letter "C". It is important to understand that the CHAR variable "Dog3" contains the character representation of the letter "C", and the INTEGER variable "Index" contains the numerical value of the ASCII representation of the letter "C". It would be perfectly allright to use the variable "Index" for any desired numerical calculations, but not to display the letter "C". On the other hand, it would be allright to use the variable "Dog3" to display the letter "C" on the monitor but it could not be used for any calculations. The purpose therefore, of the two procedures "ORD" and "CHR", is to translate from one type to the other.

The variable "Cat4" is assigned the double quote by enclosing it in the single quotes, and the characters are output in a funny order to spell "CAT. The variable "Char1" is assigned the value "S", and the word is completed resulting in the full word "CATS" on the monitor after the program is compiled and run.

If this were the only way to use the CHAR type variable, it would be very tedious and frustrating, but there are other methods to use the CHAR type that are far more useful as you will see.

Next, an additional means of assigning a CHAR type variable is given. By assigning the CHAR variable "65C", it is the same as writing CHR(65), resulting in the variable having the internal value "A". A number less than 256 followed by a "C" is defined by Modula-2 as a CHAR type constant.

Finally, the variable "Char1" is assigned the letter "a" and it is converted to upper case "A" with the procedure CAP. This procedure will convert the argument to its upper case equivalent if it is a lower case letter. If its argument is an upper case letter or any other character, it will do nothing to it.

Compile and run this program and observe the output.

Using the transfer procedures

Load and display the file named TRANSFER.MOD for several examples of transferring data between the various simple data types. The transfer functions given here may not seem too important at this time, but some time spent here will help to reduce the frustration later when you get seemingly wrong errors that say you are using incompatible types in a statement. All of the program will not be discussed, only those statements that use some of the more unusual capabilities of Modula-2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
MODULE Transfer;

VAR Int1,  Int2  : INTEGER;
    Card1, Card2 : CARDINAL;
    Real1, Real2 : REAL;
    Char1        : CHAR;

BEGIN

   Int1  := 14;
   Int2  := 35;
   Card1 := Int1 + Int2 + 23;               (* assignment compatible *)
   Card2 := Card1 - 13 * 2 + VAL(CARDINAL,Int1);  (* mixed types     *)
   Card2 := Card1 - 13 * 2 + VAL(CARDINAL,Int1);  (* assignment comp *)
   Int1  := Int2 * VAL(INTEGER,Card1);

   Real1 := 12.0;
   Real2 := Real1 + FLOAT(Card2) * 1.112;        (* CARDINAL to REAL *)
   Real2 := Real2 + FLOAT(Int1);                 (* INTEGER to REAL  *)

(* Int1  := TRUNC(Real1) + Int2 * 3;            Incompatible error 1 *)
   Int1  := TRUNC(Real1) + VAL(CARDINAL,Int2) * 3;    (* error fixed *)
   Int1  := VAL(INTEGER,TRUNC(Real1)) + Int2 * 3;     (* error fixed *)

(* Card1 := TRUNC(Real1) + Int2 * 3;             Incompatible error 2 *)
   Card1 := VAL(INTEGER,TRUNC(Real1)) + Int2 * 3;      (* error fixed *)
   Card1 := TRUNC(Real1) + VAL(CARDINAL,Int2) *3;      (* error fixed *)

   Char1 := "A";
(* Int1  := ORD(Char1) + Int2;                   Incompatible error 3 *)
   Int1  := VAL(INTEGER,ORD(Char1)) + Int2;            (* error fixed *)
   Int1  := ORD(Char1) + VAL(CARDINAL,Int2);           (* error fixed *)

   Card1 := ORD(Char1) + Card1;
   Real2 := FLOAT(ORD(Char1)) + 1.2345;

   Char1 := CHR(TRUNC(FLOAT(ORD(Char1))));          (* Sheer Nonsense *)

END Transfer.

In line 12, the calculations are done in INTEGER format, but due to the assignment compatibility of INTEGER and CARDINAL, the result is converted to CARDINAL across the ":=".

In lines 13 to 15, the Modula-2 standard procedure VAL is used to convert INTEGER values to CARDINALS and vice versa. Using the VAL function, you can convert any simple type value to another.

Lines 18 and 19 illustrate the standard procedure FLOAT which converts an INTEGER or CARDINAL type variable to a REAL type variable.

The expression in line 21 is an error because the standard procedure TRUNC results in a CARDINAL which cannot be added to an INTEGER. Therefore this line is commented out. Either of the next two lines fix the problem by making the addition type-compatible then making use of the assignment compatibility between INTEGER and CARDINAL for line number 22. The same error occurs in line 25 and is fixed the same way in either of the next two lines. Once again, in line 30, the incompatible type error occurs and is fixed in either of two ways in the next two lines.

Lines 34 and 35 illustrate converting CHAR data to first CARDINAL then REAL which requires nested procedure calls. The last line of the program is a nest of procedures which converts a character from CHAR to CARDINAL, then to REAL, back to CARDINAL, and finally back to the original CHAR variable. It does nothing except act as a good illustration to you of what can be done.

Conversion between types is very important. You will use these techniques often so it is important to know how they work. A very simple yet helpful memory aid is to remember that any simple type can be converted to CARDINAL and CARDINAL can be converted to any type. Most other conversions require two steps to get from one to the other.

Remember that

    INT(...)       = VAL(INTEGER, ...);
    ORD(...)       = VAL(CARDINAL, ...);
    FLOAT(...)     = VAL(REAL, ...);
    LFLOAT(...)    = VAL(LONGREAL, ...);
    TRUNC(...)     = VAL(CARDINAL, ...);

Chapter 14 will readdress this topic with even more extensive type transfer procedures.

Programming problems

  1. Write a program in which you define, using the CHAR type variable, the letters "a" and "z", and the numbers "0" and "9". Convert them to CARDINAL, and display the four characters and their ASCII (numerical) values.
  2. Write a program that you can easily modify to experiment with conversions between the various types that result in incorrect conversions to see the results on your compiler. For example, convert a -1 as an INTEGER to a CARDINAL.

 

Next: Chapter 4. Loops and Control Structures