Pointers store memory addresses. Their value is an integer.
int x = 10; // A variable int *p; // A pointer to an integer p = &x; // & (address-of): p now holds the address of x *p = 20; // * (dereference): the value at the address p points to is now 20. x is now 20! p++; // Pointer arithmetic: moves pointer to the next memory slot of its type.
Memory must be manually allocated and freed from the heap.
int *arr = (int*)malloc(10 * sizeof(int)); // ... use the array ... free(arr); // Always free what you malloc!
Group related data. `typedef` creates a convenient alias.
typedef struct { char name[50]; int id; } Student; Student s1; strcpy(s1.name, "Alex"); s1.id = 123;
A string is just a `char` array ending with a null terminator `\0`.
char greeting[] = "Hello"; // Size 6 ('H','e','l','l','o','\0') int numbers[5] = {1, 2, 3, 4, 5};
Encapsulates data (private) and operations (public).
class Rectangle { private: int width, height; public: // Constructor Rectangle(int w, int h) : width(w), height(h) {} int area() { return width * height; } // Destructor ~Rectangle() { // Cleanup code here } };
Use `new` to allocate and `delete` to deallocate.
Rectangle *r = new Rectangle(5, 10); // ... use the object via r->area() ... delete r; // Deletes a single object int *arr = new int[50]; delete[] arr; // Deletes an array of objects
Build new classes from existing ones. `virtual` enables dynamic behavior.
class Shape { public: virtual void draw() { /*...*/ } }; class Circle : public Shape { public: void draw() override { /* Draw a circle */ } };
Everything is an S-expression in prefix notation. Avoids side effects.
; (operator operand1 operand2 ...) (+ 10 (* 2 5)) ; Evaluates to 20
`'()` is the empty list, and it is the only value that is not `#t` in a boolean context.
| Form | Purpose |
|---|---|
(define name value) |
Global binding |
(define (f x) body) |
Function definition |
(lambda (params) body) |
Create an anonymous function |
(let ((n v)) body) |
Local binding |
(if test then else) |
Conditional |
The fundamental data structure is the pair, built with `cons`.
(cons 1 2) ; -> '(1 . 2) (a pair) (cons 1 '()) ; -> '(1) (a list) (cons 1 '(2 3)) ; -> '(1 2 3) (car '(1 2 3)) ; -> 1 (first element) (cdr '(1 2 3)) ; -> '(2 3) (rest of the list)
Functions that take other functions as arguments.
; Apply (* 2) to each element (map (lambda (x) (* x 2)) '(1 2 3)) ; -> '(2 4 6) ; Keep only even numbers (filter even? '(1 2 3 4)) ; -> '(2 4)