I would like to return two double variables: when calling a function that I have created. According to some tutorials (which deal with the basics of the C++), I would be unable to do that.
Is there a way to do so?
In C or C++, we cannot return multiple values from a function directly.
No, you can not have two returns in a function, the first return will exit the function you will need to create an object.
If we want the function to return multiple values of same data types, we could return the pointer to array of that data types. We can also make the function return multiple values by using the arguments of the function.
You could write a simple struct that holds the variables and return it, or use an std::pair
or std::tuple
:
#include <utility> std::pair<double, double> foo() { return std::make_pair(42., 3.14); } #include <iostream> #include <tuple> // C++11, for std::tie int main() { std::pair<double, double> p = foo(); std::cout << p.first << ", " << p.second << std::endl; // C++11: use std::tie to unpack into pre-existing variables double x, y; std::tie(x,y) = foo(); std::cout << x << ", " << y << std::endl; // C++17: structured bindings auto [xx, yy] = foo(); // xx, yy are double }
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