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.

Exam Tip: Remember that non‑composite types are atomic; they cannot be broken down further. If you see a type that looks like a single value, it is likely a non‑composite type.

Defining a Non‑Composite Type

  1. Choose a meaningful name that describes the data.
  2. Use the type keyword followed by the new name and the underlying type.
  3. 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.
Exam Tip: When you see a declaration like 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';
Exam Tip: When defining a new type, always choose a name that tells the reader what the value represents. This makes your code easier to read and reduces the chance of mistakes during the exam.

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.

Exam Tip: Think of non‑composite types as “name tags” for values. They give meaning but can’t hold other tags inside them.

Revision

Log in to practice.

2 views 0 suggestions