int a;int b;int c;
If i want to return a, b, and c. how I should do that? I did the following way. but it gives me error.
return a, b, c;
int a;int b;int c;
If i want to return a, b, and c. how I should do that? I did the following way. but it gives me error.
return a, b, c;
If i want to return a, b, and c. how I should do that?
Option 1
Define a struct
and return an object of the struct
.
struct MyStruct
{
int a;
int b;
int c;
};
Now you can use:
return MyStruct{10, 20, 30};
Option 2
Use std::tuple
.
using MyData = std::tuple<int, int, int>;
and then
return MyData{10, 20, 30};
While C++ doesn't allow you to return multiple values, you can return std::tuples, which are basically the same:
http://en.cppreference.com/w/cpp/utility/tuple
Or, if you want to be a bit more explicit, you can return a struct.
Alternatively, you can take an "output argument" by reference and overwrite it:
void returnTwoThings(int& out1, int&out2) {
out1 = 42;
out2 = 16;
}
int a = 0;
int b = 0;
returnTwoThings(a, b);
// Prints "a: 42 b: 16"
std::cerr << "a: " << a << " b: " << b << std::endl;
You can either return a struct
containing all three integers
struct IntTrio
{
int a;
int b;
int c;
}
IntTrio foo()
{
int a, b, c;
// ...
return {a, b, c};
}
You can also return an std::tuple<int, int, int>
, though the brace syntax for return won't work in C++14, you will need std::make_tuple
Or you can simply return your favorite fixed-sized container, such as std::array<int, 3>
containing all three values.
In C++ or C, you can return only one value/variable. If you are returning an integer it should be only one 'int'
. If you want to return multiple values, put those values in a 'struct'
(structure) and change the return type of the function and proceed with returning the 'struct'.
struct StructureName
{
int a;
int b;
int c;
};
struct StructureName functionName(input_arguments)
{
struct StructureName var;
////your operations
var.a=10;
var.b=20;
var.c=30;
return var;
}
Technically in C++ you can only return a single value from a function. To return more values you need to wrap them in a structure. Luckily the standard provides a type for this:
You can use std::tuple
to return multiple values.
std::tuple<int,int,int> getStuff()
{
return {2, 3, 4};
}
int main()
{
int x,y,z;
// Don't need to use a tuple object to catch the result.
// You can use std::tie to extract the values directly.
std::tie(x, y, z) = getStuff();
// If you don't want to use one of the values use `std::ignore`
std::tie(x, std::ignore, z) = getStuff();
// Or you can store them in a tuple.
auto tup = getStuff();
}