Reputation: 75
Is it possible to return a return statement in C++ or to do something with similar functionality?
This would be handy if, for example, there are several functions in the code which take a pointer as an input and each of them checks if the pointer is a nullptr or not. If it is a nullptr the function should stop whatever it is doing and return 0
, or whatever is appropriate for its type.
Let inputPtr
be an int*
given to a function which returns an int
. Instead of writing things like
...
if(inputPtr == nullptr) {
return 0;
}
...
every time, it would be cool to just have
...
checkNull(inputPtr);
...
or something similar. In this example it's not too bad of course, but imagine a more elaborate testing function.
Conceptually, this seems to be quite weird. But usually there is a way to prevent repetition.
Upvotes: 4
Views: 196
Reputation: 162
I think there are three options basically:
gsl::not_null
here you have good post about it. https://www.bfilipek.com/2017/10/notnull.html (of course it is not perfect solution but it may save you some time:))
Upvotes: 1
Reputation: 93496
No, it is not possible, and hiding control flow might be considered a bad idea in any event. If you have to write the checking function, it is simple enough to make that return a Boolean then:
if(checkNull(inputPtr)) return 0 ;
Upvotes: 7
Reputation: 62583
Unfortunately, this is one the very few things which can only be solved with macro in C++.
That is, you really can't stand extra if
in the code and you have a wide contract, which allows for nullptr
s to be given as arguments.
I personally would not use macro and would just use clear if
statements.
Upvotes: 1