C++ References

🔁 C++ References – Give Another Name to the Same Value

In C++, a reference lets you create another name for a variable. Think of it as a nickname — both the real name and the nickname point to the same person (or value in this case). 😄

📌 Key Points About References

  • Declared using & symbol
  • Must be initialized when created
  • Changes to reference = changes to original variable

🔧 Example: Reference to an Integer

#include <iostream>
using namespace std;

int main() {
    int original = 100;
    int &ref = original; // ref is a reference to original

    ref = 200; // Changes original too!

    cout << "Original: " << original << endl;
    cout << "Reference: " << ref << endl;

    return 0;
}
  

Try It Now

🧠 Why Use References?

  • To pass variables to functions without copying
  • To return multiple values from functions
  • For cleaner syntax compared to pointers

🔄 Reference vs Pointer

  • Reference must always refer to something
  • Pointer can be null
  • Reference syntax is easier and safer

💡 Summary

  • References are alternative names for existing variables
  • Changes to a reference affect the original variable
  • Great for function parameters and cleaner code

Use references when you want one thing with two names, and no need to mess with memory like pointers. 🧼✨