Example: Here is an example of a constructive definition of a type system: A type expression may be inductively defined as follows:
Example: The arithmetic operator + expects integer operands, so the type checker must verify that its operands are integers
Type checking requires establishing rules for type equivalence, type compatibility, and type inferencing
typedef link struct *cell; link next, last; struct *cell p; struct *cell q,r;
typedef stack_element int stack_element pop(Stack *); int a = pop(myStack); // type error? typedef fahrenheit int typedef celcius int fahrenheit f; celcius c; c = f; // type error?In the stack example, most programmers probably consider it okay to assign the result of pop to a, and would be annoyed if the compiler raised a type error. In contrast, the intent of the type declarations in the second example seems to be to create two separate types representing two different temperature systems, and we would probably want the compiler to raise a type error for the assignment of f to c.
subtype stack_element is integer; // loose name equivalence type celsius_temp is new integer; // strict name equivalence type fahrenheit_temp is new integer; // strict name equivalenceNote that the first declaration defines stack_element as a subtype of integer, thus implying the two types are similar. In contrast the last two declarations introduce new types.
int x; float y = 6.3; x = (int)y;
int x; short y; y = x;The C compiler does an implicit coercion by taking the low-order 15 bits of x and assigning them to y. It also preserves the sign bit. This works well if the value of x fits in 15 bits and poorly otherwise.
Superclass *p = new Subclass(); Subclass *s = dynamic_castA dynamic cast is not checked until run-time and may cause either a run-time error, or some error value. In C++, the return result of an invalid cast is a null pointer. Note that this is different than a static cast, where the compiler will perform the downcast from a superclass to a subclass and hope for the best.
(p); // success Superclass *p = new Superclass(); Subclass *s = dynamic_cast (p); // failure--null ptr returned