Learn Guide

C / C++ Essentials

Memory, pointers, and systems programming fundamentals.

What is C/C++?

C is a foundational procedural language used in operating systems, embedded systems, and performance-critical software. C++ extends C with classes, templates, and the Standard Library while maintaining full C compatibility.

Variables & Basic Types

int    count  = 10;
float  price  = 9.99f;
double pi     = 3.14159;
char   letter = 65;       // ASCII value 65
int    arr[5] = {1, 2, 3, 4, 5};

Pointers

int  x   = 42;
int* ptr = &x;    // ptr stores the address of x
int  val = *ptr;  // dereference: val = 42
*ptr = 100;       // modifies x through the pointer

C++ References

int x = 10;
int& ref = x;  // ref is an alias for x — cannot be null or re-seated
ref = 20;      // x is now 20

void increment(int& n) { n++; }  // modifies the original

Control Flow

if (x > 0) { } else { }

for (int i = 0; i < n; i++) { }
while (condition) { }
do { work(); } while (condition);

switch (code) {
    case 1: DoA(); break;
    case 2: DoB(); break;
    default: break;
}

Functions

int add(int a, int b) { return a + b; }

// C: pass pointer to modify original
void increment(int* n) { (*n)++; }

// C++: pass by reference
void doubleVal(int& n) { n *= 2; }

// C++: default parameter
int repeat(int times = 1) { return times; }

Memory Management

// C — manual heap allocation
int* arr = (int*)malloc(10 * sizeof(int));
free(arr);

// C++ — new / delete
int* arr2 = new int[10];
delete[] arr2;

Always free what you malloc and delete[] what you new[]. Failing to do so causes memory leaks.

C++ Classes

class Rectangle {
public:
    double width, height;
    Rectangle(double w, double h) : width(w), height(h) {}
    double area() const { return width * height; }
};

Rectangle r(3.0, 4.0);
double a = r.area(); // 12.0