Functions and Pointers
int add(int a, int b) {n return a + b;n}nnint total = add(2, 3); // 5
Pass by value vs pass by reference
void double_it(int value) {n value = value * 2; // only changes the local copyn}nnvoid double_it_ref(int &value) {n value = value * 2; // changes the caller's actual variablen}nnint score = 10;ndouble_it(score);nstd::cout << score; // still 10ndouble_it_ref(score);nstd::cout << score; // now 20
By default, C++ passes a copy of a variable into a function — changes made inside the function have no effect on the original. Adding & to a parameter makes it a reference instead, meaning the function operates on the original variable directly. This distinction doesn’t exist in Python or JavaScript in the same explicit way, and it’s one of the more important things to internalize early in C++.
Pointers
int score = 90;nint* scorePtr = &score; // stores the memory address of scorenstd::cout << *scorePtr; // dereference: prints 90n*scorePtr = 95; // changes score itself, through the pointernstd::cout << score; // 95
A pointer holds a memory address rather than a value directly. & gets the address of a variable; * (dereferencing) accesses the value stored at that address. This is C++’s most powerful — and most error-prone — feature, so take your time with it and expect to come back to this lesson more than once as later material builds on it.
A dangerous mistake: dangling pointers
A pointer that still holds the address of memory that has already been freed is called a dangling pointer, and using it produces undefined behavior — sometimes it appears to work, sometimes it crashes, sometimes it silently corrupts unrelated data. This exact class of bug is a large part of why modern C++ (covered in the memory management lesson later in this course) has moved toward smart pointers that manage this automatically.