Pointers
Null Pointer
nullptr means a pointer is not pointing at an object.
Null Pointer
null_pointer.cpp
#include <iostream>
int main() {
bool hasValue = ;
int value = ;
int fallback = -1;
int* maybeValue = nullptr;
if (hasValue) {
maybeValue = &value;
}
int result = fallback;
if (maybeValue != nullptr) {
result = *maybeValue;
}
std::cout << "hasValue=" << hasValue << std::endl;
std::cout << "result=" << result << std::endl;
return 0;
}
#include <iostream>
int main() {
bool hasValue = ;
int value = ;
int fallback = -1;
int* maybeValue = nullptr;
if (hasValue) {
maybeValue = &value;
}
int result = fallback;
if (maybeValue != nullptr) {
result = *maybeValue;
}
std::cout << "hasValue=" << hasValue << std::endl;
std::cout << "result=" << result << std::endl;
return 0;
}
#include <iostream>
int main() {
bool hasValue = ;
int value = ;
int fallback = -1;
int* maybeValue = nullptr;
if (hasValue) {
maybeValue = &value;
}
int result = fallback;
if (maybeValue != nullptr) {
result = *maybeValue;
}
std::cout << "hasValue=" << hasValue << std::endl;
std::cout << "result=" << result << std::endl;
return 0;
}
#include <iostream>
int main() {
bool hasValue = ;
int value = ;
int fallback = -1;
int* maybeValue = nullptr;
if (hasValue) {
maybeValue = &value;
}
int result = fallback;
if (maybeValue != nullptr) {
result = *maybeValue;
}
std::cout << "hasValue=" << hasValue << std::endl;
std::cout << "result=" << result << std::endl;
return 0;
}
#include <iostream>
int main() {
bool hasValue = ;
int value = ;
int fallback = -1;
int* maybeValue = nullptr;
if (hasValue) {
maybeValue = &value;
}
int result = fallback;
if (maybeValue != nullptr) {
result = *maybeValue;
}
std::cout << "hasValue=" << hasValue << std::endl;
std::cout << "result=" << result << std::endl;
return 0;
}
#include <iostream>
int main() {
bool hasValue = ;
int value = ;
int fallback = -1;
int* maybeValue = nullptr;
if (hasValue) {
maybeValue = &value;
}
int result = fallback;
if (maybeValue != nullptr) {
result = *maybeValue;
}
std::cout << "hasValue=" << hasValue << std::endl;
std::cout << "result=" << result << std::endl;
return 0;
}
nullptr
Check a pointer before dereferencing when it might be `nullptr`.