|
|
View previous topic :: View next topic |
Author |
Message |
Guest
|
subroutine return values |
Posted: Tue Mar 18, 2008 7:00 am |
|
|
Hi,
I am a newbi and have a question about subroutines:
I get values via an external A/D converter.
My main programme goes to the subroutine which reads my values and I determine the minimum and the maximum value.
How can I return this two values to my main programme?
Thank you! |
|
|
RLScott
Joined: 10 Jul 2007 Posts: 465
|
Re: subroutine return values |
Posted: Tue Mar 18, 2008 9:42 am |
|
|
If the Min and Max are 16-bit numbers, then you could pack them into the high and low words of an int32 return value. That way one int32 return value can contain two 16-bit numbers, and you can unpack them when the subroutine returns. However, a better solution may be to define two dedicated static variables, valMin and valMax. Set them in the subroutine, then don't return anything. The main program would just read valMin and valMax. The only disadvantage of that is that it uses more RAM, and PICs often are short on RAM. When you return a value in a subroutine, that value is in a RAM location that is reused by other code in your program, so it does not use use up the RAM in the same way.
Robert Scott
Real-Time Specialties |
|
|
ckielstra
Joined: 18 Mar 2004 Posts: 3680 Location: The Netherlands
|
|
Posted: Tue Mar 18, 2008 10:28 am |
|
|
Option 3: return a structure
Code: | struct Foo
{
int16 Min;
int16 Max;
} ;
struct Foo CalcMinMax()
{
struct Foo A;
A.Min = 1;
A.Max = 100;
return A;
}
void main(void)
{
struct Foo B;
B = CalcMinMax();
printf("Minimum = %d, Maximum = %d", B.Min, B.Max);
while(1);
} |
Option 4: Pass pointer to the return values as function parameters. Code: | void CalcMinMax(int8 NewVal, int8 *Min, int8 *Max)
{
if (NewVal > *Min)
*Min = NewVal;
if (NewVal > *Max)
*Max = NewVal;
}
void main(void)
{
int8 Min, Max;
CalcMinMax(100, &Min, &Max); // Note the '&' to pass the variable's address.
printf("Minimum = %d, Maximum = %d", Min, Max);
while(1);
} |
Option 5: A variation on option 4; pass by reference.
Pointers are sometimes difficult to read, that's when 'reference variables' are an option. Code: | void CalcMinMax(int8 NewVal, int8 &Min, int8 &Max) // Note the '&' instead of '*'
{
if (NewVal > Min)
Min = NewVal;
if (NewVal > Max)
Max = NewVal;
}
void main(void)
{
int8 Min, Max;
CalcMinMax(100, Min, Max); // Note the missing '&'
printf("Minimum = %d, Maximum = %d", Min, Max);
while(1);
} |
|
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|