C++ Programming Tutorial

Learn modern C++ step-by-step with concise explanations and practical examples. Navigate topics from basics to advanced features using the sidebar.

Pointers and References

Pointers store memory addresses; references are aliases to existing variables. Use references for safe parameter passing; use pointers for optional values, arrays, and dynamic memory.

Basics
#include \n\nint main(){\n    int x = 10;\n    int* p = &x;      // pointer to x\n    int& r = x;       // reference to x\n\n    std::cout << *p << " " << r << "\n";\n\n    p = nullptr;      // pointer can be null, reference cannot\n    return 0;\n}
Notes
  • Use `nullptr` instead of `NULL`.
  • Prefer references for non-nullable parameters.
  • For dynamic memory, prefer RAII and smart pointers (`std::unique_ptr`).

Keep Practicing

Use the online compiler to run examples and test variations. Reinforce learning by building small programs for each topic.