Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to "return a return statement"?

Tags:

c++

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.

like image 524
tz39R Avatar asked Dec 31 '22 19:12

tz39R


2 Answers

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 ;
like image 59
Clifford Avatar answered Jan 13 '23 15:01

Clifford


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 nullptrs to be given as arguments.

I personally would not use macro and would just use clear if statements.

like image 35
SergeyA Avatar answered Jan 13 '23 17:01

SergeyA