Today I did a funny mistake in my C++ code. I have a function with two arguments of type std::vector<int>::iterator& (i and j). Iterators should point to same vector. Function should return sum of two numbers in the vector, and move both iterators forward to j+1th position of vector:
int exp_func_add::evaluate(vector<int>::iterator& i, vector<int>::iterator& j) {
int result = *i + *j;
++j;
i = j;
return result;
}
First I wrote this code:
int exp_func_add::evaluate(vector<int>::iterator& i, vector<int>::iterator& j) {
++j;
i = j;
return (*i+*j); // <====== Oops !
}
We know that return statement returns control to caller. My question is why C++ standard does not define a late value return semantics? Let's call it late_return keyword:
int exp_func_add::evaluate(vector<int>::iterator& i, vector<int>::iterator& j) {
late_return *i+*j; // Hold return value but don't go back
// to the caller until leaving scope
++j;
i = j;
}
This question may get hundreds of downvotes (not constructive, blah blah). Though I would like to ask some questions:
Not really, though your first code sample is fairly idiomatic C or C++ code.The "assign a value to "result", and then have 'return result' as the last statement of the function is avery common pattern.
No, because it adds complexity without any clear benefit over the existing idiom. It'd add a whole bunch of edge cases to the language, too. Functions can have more than one return statement, so how so you handle multiple late_return statements? First one wins? Last one wins? Throw an exception? What about a code path that includes late_return and return?
The closest thing I can think of is constraints languages or logic languages like Prolog, where the "result" is produced as soon as all of the data necessary to produce it has been provided.
Is there a way to simulate this behavior using macros or any other tricks?
Yes, and you said it yourself: define a variable called ret and return it at the end. That's only one line more and it's a lot more clear what is going on when you get to the end of the function.
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