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.
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 ;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With