tuple< double, double > calc(double);
cin >> avg;
auto t = calc( avg );
cout << get<0>(t) << ", " << get<1>(t) << endl; // consider using std::tie perhaps
tuple< double, double > calc(double avg)
double a, b;
a = avg;
b = avg + 2;
return make_tuple(a, b);
This is related to dhayden's option 1.
The objection was, a long time ago, that returning a class by value takes time for the copy. Modern optimizers cause this issue to evaporate. The objection comes from a I time I remember when 64 MBytes of RAM was over $1,000 (that's Mega, not Giga), and the compiler couldn't breathe. We were lucky if it could process templates at all with such little RAM.
Goodness it took a while to mention tuples. (Props to Niccolo!)
C++17 has structured bindings added to the language, so you can simply say:
auto [a, b] = f( whatever );
cout << a << ", " << b << "\n";
Structured bindings work over structs and classes as well, as long as there is a clear way for the compiler to decipher which member objects are meant. (Otherwise you'll have to define a couple of other functions as part of your class's API to help it along.)
Can we try and remember that we're in the beginner's forum here, please? Rather than writing snide, unhelpful answers effectively mocking the OP for not understanding that you can't literally return 2 values in C++, perhaps we could be a bit kinder and more understanding in helping the OP find a solution to the problem?
Um, one person in this thread chose to respond as if the OP was genuienly asking to have the C++ standard changed, rather than showing any attempt to help them achieve what they actually wanted to achieve. That's unhelpful and, frankly, mean-spirited.
easier for you to create a whole new programming language
Umm ... it's called Python. (And, as @Niccolo picked up on, there it would be returned as a tuple, albeit with far simpler syntax.)
Which, I suspect, is where this (and a number of other beginner threads) are coming from. Universities are increasingly using Python as an initial teaching language, particularly for engineers and scientists, so one may need to be aware of pythonic (but completely non-C++) idioms, like
a, b = c, d
if a <= x <= b
return (a, b)
And you would be hard pressed to tell a student that (C++): for ( constauto &x : S )
is more readable than (Python): for x in S: