0
0
C++programming~30 mins

Reference vs pointer in C++ - Hands-On Comparison

Choose your learning style9 modes available
Understanding Reference vs Pointer in C++
📖 Scenario: Imagine you have a box with a number inside. You want to create two ways to access and change this number: one using a reference (like a nickname for the box) and one using a pointer (like a map showing where the box is).
🎯 Goal: Learn how to create and use a reference and a pointer to the same integer variable, and see how changing the value through each affects the original variable.
📋 What You'll Learn
Create an integer variable named number with the value 10.
Create a reference to number named refNumber.
Create a pointer to number named ptrNumber.
Change the value of number using refNumber and ptrNumber.
Print the value of number after each change.
💡 Why This Matters
🌍 Real World
References and pointers are used in C++ programs to efficiently access and modify data without copying it, such as in managing large data structures or hardware resources.
💼 Career
Understanding references and pointers is essential for C++ developers working in systems programming, game development, and performance-critical applications.
Progress0 / 4 steps
1
Create the integer variable number
Create an integer variable called number and set it to 10.
C++
Need a hint?

Use int number = 10; to create the variable.

2
Create a reference and a pointer to number
Create a reference to number named refNumber and a pointer to number named ptrNumber.
C++
Need a hint?

Use int& refNumber = number; for the reference and int* ptrNumber = &number; for the pointer.

3
Change number using the reference and pointer
Change the value of number to 20 using refNumber. Then change the value of number to 30 using ptrNumber.
C++
Need a hint?

Assign 20 to refNumber and 30 to *ptrNumber.

4
Print the value of number after changes
Print the value of number after changing it with refNumber and after changing it with ptrNumber. Use std::cout and print each value on a new line.
C++
Need a hint?

Use std::cout << number << std::endl; to print the value.