Define and use non-composite types
13.1 User‑Defined Data Types
What are Non‑Composite Types?
Think of a non‑composite type like a single Lego brick.
It can hold only one piece of information – no other bricks inside it.
In programming, non‑composite types are the *atomic* data types: int, float, bool, char, etc.
They cannot contain other values inside them.
Defining a Non‑Composite Type
- Choose a meaningful name that describes the data.
- Use the
typekeyword followed by the new name and the underlying type. - End the definition with a semicolon.
Example: Define a type for a student’s age.
type Age = int;
Now Age can be used just like int, but it adds meaning to the code.
Using a Non‑Composite Type
Once defined, you can declare variables, function parameters, and return types using the new type.
Age studentAge = 17;
void setAge(Age a) { studentAge = a; }
Age getAge() { return studentAge; }
Common Mistakes
- Using a non‑composite type to store multiple values (e.g., trying to store a list of grades in a single
int). - Defining a type with the same name as an existing keyword (e.g.,
type int = float;). - Forgetting the semicolon at the end of the type definition.
type X = Y;, check that Y is a primitive type and that X is not already used elsewhere.
Table of Common Non‑Composite Types
| Type | Description | Example |
|---|---|---|
| int | Whole numbers (e.g., 42) | int score = 95; |
| float | Numbers with decimals (e.g., 3.14) | float pi = 3.1415; |
| bool | True or false values | bool isStudent = true; |
| char | Single character (e.g., 'A') | char grade = 'A'; |
Analogy: The “Name Tag” Trick
Imagine you’re at a school fair. Each student has a name tag that says Age: 17.
The tag itself is just a piece of paper (a non‑composite type) that holds a single piece of information – the age.
You can give the tag to anyone, but you can’t put a whole list of ages on one tag.
That’s exactly how non‑composite types work in code.
Revision
Log in to practice.