# Ranges Constraints and Subtypes

##
Range Constraints

### Range Constraints

- Variable declarations can constrain the set of legal values:

procedure whatever is
x: Integer;
exam_score: Integer range 0 .. 100;
exam_average: Float range 0.0 .. 100.0;
begin
exam_score := 95; -- Okay
-- exam_score := 195; -- Error
exam_score := exam_score + 10; -- might cause error
-- exam_score := exam_score + 100; -- will cause error
get(exam_score); -- Could cause error
get(x);
exam_score := x; -- Could cause error

##
Subtypes

### Subtype Declarations

- Set of legal values can be named:

procedure whatever is
x: Integer;
subtype Possible_Exam_Score is Integer range 0 .. 100;
exam_score1: Possible_Exam_Score;
exam_score2: Possible_Exam_Score;
begin
exam_score := 95; -- Okay
-- exam_score := 195; -- Error
exam_score := exam_score + 10; -- might cause error
-- exam_score := exam_score + 100; -- will cause error
get(exam_score); -- Could cause error
get(x);
exam_score := x; -- Could cause error

Types and subtypes can be freely mixed in assignment, calls, and expressions

### What is a Type

- A type is :
- A set of values, and
- A set of operations

- Example: Integers
- A set of values: All possible integers
- A set of operations: Arithmetic ops, IO, declaration, assignment

- Example: class Pair
- A set of values: All possible pairs
- A set of operations: Methods, including inherited

### Subtypes and Type Checking

- A subtype is a subset of a type (ie subset of the values):
- A parent type, a subtype, or a sibling type can be used in a context where any are expected
- Example - all of the assignments below compile:

i: Integer;
n: Natural;
p: Positive;
begin
i := p; -- Expect integer, found positive
p := i; -- Expect positive, found integer
n := p; -- Expect natural, found positive
p := i; -- Expect positive, found integer

### What is a Subtype

- A subtype is a subset of a type (ie subset of the values):

### Anonymous Subtype

- An integer range is an anonymous subtype (ie it does not have a name)

### Subtype can be used to Rename

- A subtype can be the whole set

subtype NewName is Integer;