Back to questions
JuniorTheoryVery common
What happens when this program runs?
#include <iostream>
int* positive(int* p) {
return *p > 0 ? p : nullptr;
}
int main() {
int x = -7;
std::cout << *positive(&x) << '\n';
}Undefined behavior: positive returns nullptr, and * dereferences it
- Expecting a guaranteed crash: dereferencing
nullptris undefined behavior, and the standard promises no crash or any other outcome. - Expecting a compile error: the compiler does not check which pointer may be
nullptr, so the program builds without an error.
- How would you change
mainso that it printsxonly whenpositivedoes not returnnullptr? - Why would a reference be a poor return type for
positive?