How to return multiple values in C language?
In C language, it is not supported to directly return multiple values, but there are several ways to achieve returning multiple values.
- Struct: You can define a structure, where multiple values are members of the structure, and then return the entire structure as the function’s return value.
#include <stdio.h>
struct MultipleValues {
int value1;
int value2;
};
struct MultipleValues getValues() {
struct MultipleValues values;
values.value1 = 10;
values.value2 = 20;
return values;
}
int main() {
struct MultipleValues result = getValues();
printf("Value 1: %d\nValue 2: %d\n", result.value1, result.value2);
return 0;
}
- Pointer parameters: By passing pointer parameters, it is possible to modify the value of variables pointed to by the pointer within a function, thus achieving the return of multiple values.
#include <stdio.h>
void getValues(int* value1, int* value2) {
*value1 = 10;
*value2 = 20;
}
int main() {
int result1, result2;
getValues(&result1, &result2);
printf("Value 1: %d\nValue 2: %d\n", result1, result2);
return 0;
}
- Global variables: can define global variables and modify their values within a function to achieve the return of multiple values.
#include <stdio.h>
int value1, value2;
void getValues() {
value1 = 10;
value2 = 20;
}
int main() {
getValues();
printf("Value 1: %d\nValue 2: %d\n", value1, value2);
return 0;
}
It is important to note that when using pointer parameters or global variables, make sure to consider the scope and lifetime of the variables to prevent unexpected issues. Using structs can better encapsulate multiple values and improve code readability and maintainability.