🔗 References vs Pointers: Head-to-Head Comparison
Both pointers and references allow you to manipulate memory across function scopes, but they differ significantly in safety and syntax.
📊 Comparative Breakdown
| Feature | Pointer (int ptr) | Reference (int &ref) |
|---|---|---|
| Initialization | Optional at declaration (int p = nullptr;) | Mandatory at declaration (int &r = x;) |
| Null Ability | Can be nullptr | Cannot be null |
| Re-assignment | Can point to different variables over time | Permanent alias (cannot be rebound) |
| Syntax | Requires to dereference | Uses standard variable syntax directly |
💻 Code Example: Const Reference Efficiency
⊞C++ Source Code (main.cpp)
#include <iostream>
#include <string>
// const std::string & avoids copying a 10,000 character string!
void printLogMessage(const std::string &msg) {
std::cout << "[LOG]: " << msg << std::endl;
}
int main() {
std::string systemEvent = "Windows 11 Kernel Process Initialized Successfully";
printLogMessage(systemEvent);
return 0;
}
⊞Windows 11 Pro Terminal Execution OutputWindows 11 Pro Verified
⊞Administrator: Windows 11 Pro Command Prompt (g++ GCC 13.2.0)
—□✕
Microsoft Windows [Version 10.0.22631.3007] (Windows 11 Pro x86_64)
(c) Microsoft Corporation. All rights reserved.
C:\Users\Student\CPP_Project>#include <iostream>
C:\Users\Student\CPP_Project> g++ -o main.exe main.cpp
C:\Users\Student\CPP_Project> main.exe
Hello World from C++ on Windows 11 Pro!
[Process exited with code 0 in 0.001 seconds]