Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning two variables in a C++ function [duplicate]

Tags:

c++

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?

like image 733
Zeus M Avatar asked Mar 12 '13 15:03

Zeus M


People also ask

Can I return 2 values from a function in C?

In C or C++, we cannot return multiple values from a function directly.

Can a function return 2 variables?

No, you can not have two returns in a function, the first return will exit the function you will need to create an object.

Is it possible to return multiple values from a function?

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.


1 Answers

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 } 
like image 109
juanchopanza Avatar answered Sep 18 '22 17:09

juanchopanza