Introduction
Imagine writing a program and accidentally mixing numbers with words in a way that confuses the computer. Type checking rules help catch these mistakes before the program runs, making sure everything fits together correctly.
Imagine a kitchen where each ingredient has a label like 'vegetable' or 'spice'. Recipes require certain types of ingredients to work well. If you try to use salt where sugar is needed, the dish might fail. Type checking rules are like the recipe instructions that ensure the right ingredients are used together.
┌─────────────────────────────┐
│ Program Code │
└─────────────┬───────────────┘
│
┌───────▼────────┐
│ Type Checking │
│ Rules │
└───────┬────────┘
│
┌───────────▼───────────┐
│ Compatible Types? │
└───────┬───────────────┘
│Yes │No
│ │
┌───────▼───────┐ ┌───────▼────────┐
│ Program Runs │ │ Type Error │
│ Successfully │ │ Detected │
└───────────────┘ └────────────────┘def add_numbers(a: int, b: int) -> int: return a + b result = add_numbers(5, 10) print(result) # This will cause a type error if uncommented: # result = add_numbers(5, 'hello')
type checking rules in a compiler?int x = 5; float y = 3.2; x = y;
x is int, y is float. Assignment tries to put a float into an int.string name = "Alice"; int age = "30";
name is a string assigned a string literal, which is correct. age is an int assigned a string literal "30".int and float, which call violates type checking rules?void process(int a, float b) { /*...*/ }
// Calls:
process(10, 5.5);
process(3.2, 4.1);
process(7, 2);int then float. Call 1 passes int and float correctly. Call 2 passes float then float, which mismatches first parameter. Call 3 passes int and int, which may be allowed if int converts to float.Pass the test and this pattern moves unknown