In C, functions can only return a single value directly. However, there are several ways to return multiple values, such as using pointers, structures, arrays, and dynamic memory allocation. This guide explores these methods with examples.
Using pointers is a common way to modify multiple values inside a function and reflect the changes outside.
cCopyEdit#include <stdio.h>
void getMinMax(int a, int b, int *min, int *max) {
*min = (a < b) ? a : b;
*max = (a > b) ? a : b;
}
int main() {
int x = 10, y = 25, min, max;
getMinMax(x, y, &min, &max);
printf("Min: %d, Max: %d\n", min, max);
return 0;
}
Min: 10, Max: 25
✅ Best Use Case: When you need to modify multiple variables inside a function.
A structure groups multiple values together, allowing a function to return more than one value.
#include <stdio.h>
typedef struct {
int quotient;
int remainder;
} DivisionResult;
DivisionResult divide(int dividend, int divisor) {
DivisionResult result;
result.quotient = dividend / divisor;
result.remainder = dividend % divisor;
return result;
}
int main() {
DivisionResult res = divide(10, 3);
printf("Quotient: %d, Remainder: %d\n", res.quotient, res.remainder);
return 0;
}
yamlCopyEditQuotient: 3, Remainder: 1
✅ Best Use Case: When multiple values are logically related, making the code more structured.
An array can store multiple values and be returned via a pointer.
#include <stdio.h>
void getSquares(int num, int squares[2]) {
squares[0] = num * num; // Square
squares[1] = num * num * num; // Cube
}
int main() {
int results[2];
getSquares(4, results);
printf("Square: %d, Cube: %d\n", results[0], results[1]);
return 0;
}
Square: 16, Cube: 64
✅ Best Use Case: When returning multiple values of the same type.
Dynamically allocated memory can be used when the number of return values is unknown at compile time.
#include <stdio.h>
#include <stdlib.h>
int* getNumbers() {
int *arr = (int*)malloc(2 * sizeof(int));
arr[0] = 10;
arr[1] = 20;
return arr;
}
int main() {
int *nums = getNumbers();
printf("First: %d, Second: %d\n", nums[0], nums[1]);
free(nums); // Free allocated memory
return 0;
}
First: 10, Second: 20
✅ Best Use Case: When the number of return values is dynamic or large.
Method | Flexibility | Memory Usage | Complexity |
---|---|---|---|
Pointers | High | Low | Medium |
Structures | Medium | Low | Easy |
Arrays | Medium | Medium | Easy |
Dynamic Memory | Very High | High | Complex |
Although C does not support returning multiple values directly, using pointers, structures, arrays, or dynamic memory allocation provides effective alternatives. Choose the method that best suits your use case.