Quiz Entry - updated: 2026.07.06
How do you pass by reference in C++ vs C?
C++ passes by reference with & parameters (void f(int& a)); C simulates it with pointers (void f(int* a)).
// C++ way (cleaner)
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
swap(x, y); // just pass the variables
// C way (explicit pointers)
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
swap(&x, &y); // must pass addresses
Advantages of references:
- Cleaner syntax at the call site (no
&/*noise) - Can't be null, so no null-check needed
- No pointer arithmetic possible, so less can go wrong
When to use pointers instead:
- The argument is optional (can be
nullptr) - You need to reseat what you point at
- Working with arrays or manual dynamic allocation