C language for MSX
Column by Nicola Brogelli (Part 2)
Type Conversions
As we saw in the previous handout, in C every piece of data has a well-defined Type. When variables of different types appear in an expression, the compiler is often able to manage the conversion between types without the programmer's intervention. In other cases, however, the conversion is required to be performed explicitly by the programmer. A factor to keep in mind, when talking about conversions, is that a type conversion does not always preserve the value: for example in the conversion from float to int there is generally a loss of precision, because the representation adopted for integers is lower with that adopted for the royals. From this point of view, a distinction can be made between type conversion with loss of information and type conversion without loss of information. In particular, in the latter case we talk about type promotion and it happens when, for example, an expression of an int type is promoted to real.
Implicit conversions
When an expression of the type x or y involves operands of different types, an implicit conversion occurs according to the following rules:
- when integers and reals are involved in an expression, the operands are always converted to the one of greater length.
- if an arithmetic expression is assigned to a variable of type integer or real, the result of the expression is converted to the type of variable.
- A char type or an enumeration (we'll see later) can be used wherever an integer type is required.
int r = 0;
float a = 10.25;
float b = 3.11;
r = a + b; // The result of r = 13
Explicit conversions
This type of conversion is the responsibility of the programmer, who explicitly requests to convert a value from one type to another. The conversion operation, also defined as cast, consists of the name of the type of the variable to which the conversion must be carried out, written in round brackets and placed in front of the value or variable to be converted.
int i = (int) 3.14;
float p = 3.14;
int i = (int)p; In both cases the value of i will be 3.
If the content satisfied you, here you can find it third dispensation.
For those interested theMSX Italy Association created a R&D working group on C programming for MSX. For more info:associazioneMSXitalia@gmail.com




0 Comments