Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Late return value in C++

Tags:

c++

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:

  1. Is there a way to simulate this behavior using macros or any other tricks?
  2. Do this deserve an implementation or to be considered as a feature in next c++ standard?
  3. Are there programming languages implementing similar feature?
like image 440
sorush-r Avatar asked Sep 11 '26 21:09

sorush-r


2 Answers

  • Is there a way to simulate this behavior using macros or any other tricks?

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.

  • Do this deserve an implementation or to be considered as a feature in next c++ standard?

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?

  • Are there programming languages implementing similar feature?

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.

like image 149
Mark Bessey Avatar answered Sep 13 '26 11:09

Mark Bessey


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.

like image 31
Matt Avatar answered Sep 13 '26 09:09

Matt