There are at least three approaches.
The first one as you already mentioned is to return a value using a parameter of a pointer type.
For example
#include <iostream>
int minmax( int x, int y, int *max )
{
int min = x;
*max = y;
if ( y < x )
{
min = y;
*max = x;
}
return min;
}
int main()
{
int min, max;
min = minmax( 20, 10, &max );
std::cout << "min = " << min << ", max = " << max << '\n';
}
The program output is
min = 10, max = 20
Here in the program the variable max is passed by reference in the terms of C.
The second approach is to pass by reference in the terms of C++. For example
#include <iostream>
int minmax( int x, int y, int &max )
{
int min = x;
max = y;
if ( y < x )
{
min = y;
max = x;
}
return min;
}
int main()
{
int min, max;
min = minmax( 20, 10, max );
std::cout << "min = " << min << ", max = " << max << '\n';
}
The program output is the same as shown above.
And you can indeed return one object but of a compound type that contains other sub-objects. For example
#include <iostream>
#include <utility>
std::pair<int, int> minmax( int x, int y )
{
return y < x ? std::pair<int, int>( y, x ) : std::pair<int, int>( x, y );
}
int main()
{
auto p = minmax( 20, 10 );
std::cout << "min = " << p.first << ", max = " << p.second << '\n';
}
The program output also is the same as shown for the first demonstrative program.
Instead of the standard class template std::pair that has two data members you can use the class template std::tuple if you want to return more than two objects. Or you can write your own compound type (template or not template) as a structure or class.
For example
#include <iostream>
#include <tuple>
std::tuple<int, int, int> get_sorted( int x, int y, int z )
{
if ( not ( y < x ) && not ( z < x ) )
{
return not ( z < y ) ? std::make_tuple( x, y, z )
: std::make_tuple( x, z, y );
}
else if ( not ( z < y ) )
{
return not ( z < x ) ? std::make_tuple( y, x, z )
: std::make_tuple( y, z, x );
}
else
{
return not ( y < x ) ? std::make_tuple( z, x, y )
: std::make_tuple( z, y, x );
}
}
int main()
{
auto t = get_sorted( 15, 10, 20 );
std::cout << "( " << std::get<0>( t )
<< ", " << std::get<1>( t )
<< ", " << std::get<2>( t )
<< " )\n";
}
The program output is
( 10, 15, 20 )