Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to exit a function with a return value without using "return" in c++

How would I exit a function with a return value without using return.

Is there something like this in c++ :

auto random_function() {
    printf("Random string"); // Gets executed

    exit_with_return_value(/* Any random value. */);

    printf("Same string as before"); // Doesn't get executed
}

Because I’m aware about exit() which takes a exit code.
But is there any way I could exit with a return value.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It is just that I can’t call return is parentheses like this:

( return /* random value*/ );

But I can call functions in parentheses,

(exit(0));

My use case:

 template <typename ...Parameters>
 class Parameter_Pack 
 {
 private:
     void* paramsAddr[sizeof...(Parameters)];

 public:
     Parameter_Pack(Parameters ...parameters) { 
        size_t count = 0;
       
       ((
        parameters, 
        this->paramsAddr[count] = malloc(sizeof(Parameters)), 
        *(Parameters*)paramsAddr[count] = parameters, 
        count++
      ), ...);
    }

    auto operator[](size_t index) {
        size_t count = 0;
        try {
           (((count == index ? : return * 
             (Parameters*)paramsAddr[index] : * 
             (Parameters*)paramsAddr[index]), count++), ...);
         } catch (Parameters...) {
              std::cout << "Error: " << std::endl;
         }
   }

    const size_t size() const {
        return sizeof...(Parameters);
    }
};

The problem is I can’t return in auto operator[](size_t index).

The compiler error is :

"expected primary-expression before ‘return’"

>Solution :

return is a statement. Statements can’t be part of a larger expression, so you can’t return as a subexpression of some larger expression.

throw is an expression. It can be a subexpression of a larger expression, and you can throw any object you like.

It will be inconvenient for your callers, particularly if you mix it with an ordinary return. It will also not match the expectations other programmers have for how functions work. For that reason, I suggest you don’t throw when you mean return.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading