Hi,
Can someone please explain me how to make a function for returning more than one value, as in:
printf("Type some number: ");
scanf(" %i",&somenumber);
printf(Type another number: ");
scanf (" %i",&anothernumber);
What I have to do to return those two numbers from a function?
I think some struct is needed but I don't know how to implement that.
Thank you very much.
Paco
system
February 6, 2009, 2:09am
2
You can never return more than one value in C/C++. Can't be done.
You can, however, 'pass by reference' and that's the phrase you need to Google.
system
February 6, 2009, 2:12am
3
I do not know if this is the answer you where looking for but if you want one function call to change two variables, you could do this>
byte bX = 0;
byte bY = 0;
//pointer
void change1(byte* x,byte* y)
{
*x = 10;
*y = 20;
}
//reference
void change2(byte& x,byte& y)
{
x = 30;
y = 40;
}
void setup(){};
void loop()
{
change1( &bX , &by ); //bX=10,bY=20
change2( bX , bY ); //bX=30,bY=40
}
[edit]Or... Ofcourse, google what Fjornir said.[/edit]
system
February 9, 2009, 8:30pm
5
As you initially suggested, you can return a struct from a function.
Example:
struct TwoThings
{
byte Thing1;
byte Thing2;
};
void setup ()
{
}
void loop ()
{
struct TwoThings SomeThings = ReturnTwoThings(5, 10);
byte SeparateByte1 = SomeThings.Thing1;
byte SeparateByte2 = SomeThings.Thing2;
}
struct TwoThings ReturnTwoThings (byte FirstThing, byte SecondThing)
{
struct TwoThings MyTwoThings;
MyTwoThings.Thing1 = FirstThing;
MyTwoThings.Thing2 = SecondThing;
return MyTwoThings;
}
Lilbuzz
system
February 9, 2009, 9:18pm
6
Note that passing structs gets slower as the struct grows in size, because they get passed by value (in the examples above) and that means all data need to get copied.
If however a return by reference/pointer strategy is used, only the adress is copied. (a lot more efficient)
But indeed it is a possibility