I already know Java and am trying to learn C++ for for some other reasons. In a method in Java, if you don't have anything to return or there is an unreachable return line according to your logic but you just want to make the compiler happy, you just return null
. For example:
public static int[] /* This can be any Object, and returning null would work */ 5() {
for(int i = 0; i < 100; i++) {
if(i == 5) {
return new int[]{5}; // I don't know why you would want to do this, but I
// can't think of a better example.
}
}
// The compiler will give an error because there is
// no return statement, even though it is guaranteed
// to return {5}. So, for convenience, do this:
return null;
}
However, if I do return NULL
or even return nullptr
in C++, it just gives an error. Is there any way I can get around this?
Like others have pointed out, there is nullptr
. However returning a nullptr
means your return value is a pointer which means you most likely have a heap allocation inside your function that you probably don't need.
Since C++ 17 we have std::optional
which you could use as a return type for your function.
Given any non-reference return type T
you can change that return type to std::optional<T>
and instead of a nullptr
you return either std::nullopt
or {}
.
Example:
std::optional<std::string> foo(int x)
{
if (x > 10)
return "greater 10";
return std::nullopt; // or return {}
}
int main()
{
auto str = foo(12);
if (str) // check if str actually has a value or if it's null
std::cout << *str; // dereference to get the actual string
else
std::cout << "no string returned";
return 0;
}