In C, every function has a return type and zero or more parameters:
// ~~~~~ parámetros
int funcion( float );
//~~~ retorno
As a general rule, the parameters are the values with which the function is fed. However, since these parameters can be pointers, it is possible to use the parameters as a means of having the function return information to the outside. When a parameter is used for the function to return a result, it is understood that this parameter is output.
A typical example is the scanf
function:
int valor;
scanf("%d",&valor);
In this example scanf
uses the second parameter as a vehicle to return information (instead of the return
).
Why is this practice used?
The general rule dictates that the parameters must be input, however, as any general rule has its exceptions.
In the case of scanf
the reason that justifies using output parameters is that this function accepts an indeterminate number of parameters:
scanf("%d %d %d %d %d %d %d ...",&v1,&v2,&v3,...);
And with this requirement in mind, there is no standard mechanism that allows all of these values to be returned through the return type.
However, if the number of output parameters is fixed, they can be eliminated by using the return. For this we can create a structure that groups all the output values:
struct retorno
{
int val1;
int val2;
int val3;
};
// Via parametros de salida
void func(int* val1, int* val2, int* val3);
// Via return
struct retorno funcion();
At least in C, for readability, you usually choose the output parameters since the management of structures makes the source code a bit ugly. However, in C ++, where there are quite powerful utilities, the tendency is to eliminate the output parameters:
std::tuple<int,int,int> funcion()
{
// ...
}
int val1, val2, val3;
// Para recuperar los tres valores
std::tie(val1, val2, val3) = funcion();
// Si queremos ignorar algun valor
std::tie(val1, std::ignore, std::ignore) = funcion();
// C++17
auto [val1,val2,val3] = funcion();