While references are generally preferred in modern C++, there are still situations where pointers are necessary or more appropriate:
Here's an example where a pointer is used to represent the absence of a value:
#include <iostream>
void Print(const int* ptr) {
if (ptr) {
std::cout << "Value: " << *ptr << "\n";
} else {
std::cout << "Null pointer\n";
}
}
int main() {
int x = 10;
int* ptr1 = &x;
int* ptr2 = nullptr;
Print(ptr1);
Print(ptr2);
}
Value: 10
Null pointer
Answers to questions are automatically generated and may not have been reviewed.
Learn the fundamentals of references, pointers, and the const
keyword in C++ programming.