Can a C++ function return more than one value?

Can a C++ function return more than one value?

A C++ function can return only one value. However, you can return multiple values by wrapping them in a class or struct.

struct Foo
{
     int value1;
     int value2;
};

Foo SomeFunction()
{
    Foo result = { 5, 4 };
    return result;
}

Or you could use std::tuple, if that is available with your compiler.

#include <tuple>

std::tuple<int, int, int> SomeFunction()
{
    return std::make_tuple(5, 4, 3);
}

If you dont know in advance how many values youre going to return, a std::vector or a similar container is your best bet.

You can also return multiple values by having pointer or reference arguments to your function and modifying them in your function, but I think returning a compound type is generally speaking a cleaner approach.

You can only return one value in C++. If you need to return more information, return a structure (or a container like a std::vector for example), or pass in some variables as non-const references (or pointers) and change those.

Can a C++ function return more than one value?

tried using return(5,4); but this is an syntax error.

That is not a syntax error. (5,4) is a valid expression and here , is an operator. So the expression (5,4) evaluates to the rightmost operand, which is 4. Hence it will return 4.


Now coming to your problem: define a struct if any existing one doesnt help you, and return an object of struct instead, as:

struct values
{
   int i;
   int j;
   char *other;
};

values f()
{
  values v = {/*....*/};
   //...
   return v;
}

And if type of all values is same, then you can use std::vector as:

#include <vector>  //must include it!

std::vector<int> f()
{
   std::vector<int> v;
   v.push_back(5);
   v.push_back(4);
   //so on
   //...
   return v;
}

There are other containers as well, viz. std::map, std::list, std::stack, etc. Use which suits you the best. There is also std::pair which holds only two values, as the name implies.

Leave a Reply

Your email address will not be published.