FUNCTION RETURNING MORE THAN ONE VARIABLE
Yes, it can. Actually it’s not a concept in
any of the programming languages like c,c++. It is a method of using the
pointers in different way. it is only applicable for the programming languages
which has the pointer concepts. To understand this method you have to know
about pointers first.
To use this method first you have define a
function which can be a any of the return type with necessary parameters.
e.g.
int add(int a,int b)
but unfortunately this function can return
only one value. But you need two value to be return from the function.
Say for example there is function which
have to return both the number of digits and sum of the digits from a
number. First keep any of the return value as main return value of the
function.
Int sum_count_of_digit(int number)
{
Return sum;
}
This function can only return the sum. To
get the count of the digits first you have to declare a variable before the
function call. It can be either a global variable or a local variable.
Int count=0;
Int sum=Sum_count_of_digit(number);
Function:
Int sum_count_of_digit(int number)
{
Return sum;
}
Then u have to pass the variable as
parameter to function but not as normal parameter. As an address to the
function.
Int count=0;
Int sum=Sum_count_of_digit(number,&count);
But in function declaration you have to
declare the parameter as pointer. The declaration of the function is given
below.
Int sum_count_of_digit(int number,int *
count);
In the function if you increment the count
value the main value which is outside of the function is incremented. At the
end of the function the sum of the digits is returned. So obviously you can get
the both values from the function.
Int count=0,number=158;
Int
sum=Sum_count_of_digit(number,&count);
Function:
Int sum_count_of_digit(int number,int
*count)
{
For()
{
*count++; //loop
for counting the digit
}
Return sum; //returns
the sum of the digits
}
I hope you clearly understood the method...
if you have any doubt and questions comment below. In my next post I will tell
more about images and creating a image viewer on your own.
Author
Saravanakumar S
Embedded Project Engineer
No comments:
Post a Comment