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.
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'"
CodePudding user response:
This doesn't answer your question directly, but instead of reinventing the wheel why not unpack the parameter pack into an std::tuple
. You can then use std::get
to access the object
's by index.
#include <iostream>
#include <tuple>
template<typename ...Args>
static void unpack(Args&& ...args)
{
std::tuple pack{ std::forward<Args>(args)... };
int first = std::get<0>(pack);
std::cout << first << '\n';
const std::string& second = std::get<1>(pack);
std::cout << second << '\n';
bool third = std::get<2>(pack);
std::cout << std::boolalpha << third << '\n';
}
int main()
{
unpack(42, std::string{ "Some string" }, false);
}
CodePudding user response:
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
.