How to write a C-language function with multiple return values

Source: Internet
Author: User

1 Introduction

I have been engaged in C language teaching for many years, in teaching students often ask how to write a C language function with multiple return values. Writing a function with multiple return values is not a point of reference in any of the C language textbooks, but we are likely to encounter such problems in the course of teaching and application. Some students also try a lot of methods: such as the number of values that need to be returned to the corresponding processing into a return statement can be returned data, and then in the key function to disassemble the returned data into several values, or a function that needs to return multiple values to separate several functions to achieve the return of multiple values. Although these methods can finally realize the multiple values of the return requirement, it is obviously not ideal to consider the rationality and optimization of the program algorithm. We know that the return value of the C function is implemented by the return statement in the function, but each time the function is called, the return statement can return only one value. So when we want to return multiple values from a function, what is the reasonable way to achieve it? In the course of teaching, I suggest that students jump out of the set thinking of the return statement and guide them through several indirect ways to implement the C language function of multiple return values. The following is the author in the teaching process to guide students to use three different methods of writing multiple return values of C language functions.

2 Method 1: Take advantage of global variables

Analysis: Global variables as a knowledge point of C language, although we all understand its characteristics, but in the actual teaching process is not a lot of application. Since the scope of a global variable is defined from the start of the variable until the end of the program, and for C-language functions that have multiple return values, we can consider defining multiple values to be returned as global variables. When the function is called, the global variable is changed, and we then apply the changed global variable value to the keynote function. The value of the global variable that is changed after the function is called is a number of return values for the function. The application of the method is shown below with an example.
Example 1: Write a function to find the maximum and minimum values in 3 numbers.
Methods: The maximum and minimum values were defined as 2 global variables max, Min, and the maximum and minimum values were assigned to the global variables max and min respectively in the user-defined function. After the function call is complete, the value of the global variable's max and Min holds the value returned by the function request. The program reference code is as follows:
#include "stdio.h"
#include "conio.h"
int max,min;/* defines two global variables to hold function return values */
void max_min (int a,int b,int c)/* Defines the function to find the maximum minimum value */
{max=min=a;/* Initialize maximum minimum value */
if (max if (min>b) min=b;
if (min>c) min=c;
}
Main ()
{int x, y, Z;
printf ("Please enter 3 integers: \ n");
scanf ("%d,%d,%d", &x,&y,&z);
Max_min (x, y, z);/* Call function to find maximum and minimum values */
printf ("Maximum of three numbers:%d; minimum:%d", max,min);/* Output maximum and minimum */
Getch ();
}
The debug results are as follows:
Please enter a total of 3 integers:
5,-6,2
The maximum value in three numbers is: 5; The minimum value is: 6
Note: Although this method can implement a function with multiple return values, the global variable cannot guarantee that the value is correct (because its scope is global, it can be modified in the program scope, if an error is very difficult to find), and the global variable increases the coupling of the module between the programs, so this method should be used with caution.

3 Method 2: Passing array pointers

Analysis: In the course of teaching, we know that the transfer of C function parameters has value transfer and address transfer. When a value is passed, the keynote function copies the value of the argument to the parameter, and the parameter obtains the value run function passed from the keynote function. Changes to the value of the called function parameter during value passing cannot cause changes to the argument value. In the case of an address pass, the change in the parameter value in the called function directly results in the change of the argument value because the address is passed through in the pass process. Therefore, we can consider the multiple return value as an array element as an array of the form, and the address of the array as a function of the formal parameters, to pass the array parameters. After the function is called, the change of the parameter group element causes the argument to change, and then we get the multiple return values of the function from the changed real parameter group element. The following example demonstrates the application of this method.
Example 2: Write a function to find the maximum and minimum values of a one-dimensional shaped array, and return the maximum and minimum values to the main function.
Method: The address of the one-dimensional array is passed as a pointer, and the maximum value of the array is exchanged with the first element of the array, and the minimum value of the array is exchanged with the last element. After the function is called, the first element in the real parameter group is the maximum value of the array, and the last element in the real parameter group is the smallest value of the array, which implements the function of returning the maximum and minimum values of the arrays. The program reference code is as follows:
#include "stdio.h"
#include "conio.h"
void max_min (int *ptr,int N)/* Defines the function that evaluates to the minimum value of the array, passing the array pointer */
{int i,j,k;/*j the location where the maximum value is saved, K holds the minimum value of the position */
int *temp;/* for Exchange position */
*temp=*ptr;
for (I=0;i {
if (*ptr<* (ptr+i)/*/maximum value is exchanged with the first element */
{
K=i;
*temp=*ptr;
*ptr=* (PTR+K);
* (ptr+k) =*temp;
}
if (* (ptr+n-1) >* (ptr+i))/*/minimum value is exchanged with the last element */
{
J=i;
*temp =* (ptr+n-1);
* (ptr+n-1) =* (PTR+J);
* (ptr+j) = *temp;}
}
}
/* Call Max minimum function */
Main ()
{
int a[6],i;
for (i=0;i<6;i++)
scanf ("%d", &a[i]);
Max_min (a,6);
printf ("max=%d, min=%d\n \ n", a[0],a[5]);
Getch ();
}
The debug results are as follows:
Please enter 6 number of shapes, separated by a space:
5 8 9) 32-6 4
Max=32,min=-6

Note: This method applies to multiple return values where the data type is consistent. This method is not applicable when the return value data type is inconsistent.

4 Method 3: Passing struct-body pointers

Analysis: The structure as a difficult point in teaching, the textbook on its introduction of the content is not much, the application of the case is less and less, so the students generally grasp the structure of the situation is not ideal. In fact, writing a C-language function that returns multiple values can also be considered in the form of struct-body implementations. By means of Method 2, we know that if the data types of the returned numeric values are inconsistent, you can implement a C-language function that has multiple return values by defining a global variable, or you might consider defining the number of values returned as a struct, and then passing the pointer of the struct to the formal parameter struct pointer by passing the struct pointer. Then the modification of the formal parameter structure in the function is the modification of the real parameter structure, and the member of the argument struct that gets after the function is called is the function's multiple return values, and the application of the method is demonstrated below.
Example 3: Write a user-defined function that allows the user to enter basic information about the student (including number, Name, class, rating), and return the basic information to the main key function.
  


Methods: The students ' basic information is defined as a structure, and the pointer of the struct is passed in the user-defined function, then the input operation of the members of the structure is the input operation to the member of the real parameter structure, thus realizing multiple return values. The reference code is as follows:
#include "stdio.h"
#include "conio.h"
struct inf{/* defines student structures, including member numbers, names, classes, and overall scores * *
Char xh[12];
Char name[20];
Char class[15];
int chj;
};
Main (void)
{
struct INF A1; /* Define student struct type variables */
void xxxx (struct inf *ptr);
printf ("Please enter the school number, name, class, the overall score, separated by a space: \ n");
XXXX (&AMP;A1);/* Call function, take student struct type variable address as argument */
printf ("Study number:%s, Name:%s, class:%s, Score:%d", a1.xh, A1.NAME,A1.CLASS,A1.CHJ);
Getch ();
}
void xxxx (struct inf *ptr)/* This function implements input to struct member data */
{
Char xh1[12],name1[20],class1[15];
int chj1;
scanf ("%s%s%s%d", xh1,name1,class1,&chj1);
strcpy (PTR-&GT;XH,XH1);
strcpy (PTR-&GT;NAME,NAME1);
strcpy (PTR-&GT;CLASS,CLASS1);
ptr->chj=chj1;
}
The debug results are as follows:
Please enter the number, name, class, overall results, separated by a space:
200102lili200185
School Number: 200102, Name: LiLi, Class: 2001, Score: 85
Note: This method can be used when the function requires that multiple values returned are related to each other or if the data type of multiple values returned is inconsistent.

5 concluding remarks

For these three methods, if you want to return a number of value data type consistent, you can consider using method 2, and for the return value of different data types, if the values are interrelated, then method 3 is more appropriate; Method 1 Although in many cases can implement multiple return values of C language functions, But after all, there are many dangers in the application of global variables, so use it carefully.
Through the analysis of the above methods, in the course of teaching, when students encounter such problems, they can choose the appropriate way to implement multiple return values of C language function according to the condition of return value. In addition, if we encounter similar problems that can not be solved directly with the knowledge of teaching materials, they will basically be able to extrapolate and try to solve them by indirect means.

Reference documents
[1] rectification. C Programming (second edition) [M]. Beijing: Tsinghua University Press, 1999.
[2] Silvanpen translation. C Programming Tutorial [M]. Beijing: Mechanical Industry Press, 2000.
[3] Deng translation. Visual C + + programmer utility Daquan [M]. Beijing: China Water Conservancy and Hydropower Press, 2005.

(go) How to write C-language functions with multiple return values

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.