Methods for Returning Multiple Values from Functions in C

Nov 22, 2025 · Programming · 13 views · 7.8

Keywords: C Language | Function Return Values | Structures | Pointer Parameters | Multiple Returns

Abstract: This article provides an in-depth exploration of three primary methods for returning multiple values from functions in C: using structures to encapsulate return values, passing output values through pointer parameters, and utilizing arrays for homogeneous data returns. The paper includes detailed implementation principles, code examples, applicable scenarios, and performance characteristics, offering comprehensive technical reference for C developers.

Introduction

In C programming practice, scenarios frequently arise where functions need to return multiple values. Since C functions adhere to the single return value principle, developers must employ specific programming techniques to achieve multiple return functionality. This article systematically introduces three mainstream implementation methods and demonstrates their practical applications through detailed code examples.

Structure Encapsulation Method

Structures provide an effective way to organize related data in C. By defining structure types containing multiple members, multiple return values can be returned in a single operation. The core concept involves encapsulating multiple return values within a structure instance.

struct Tuple {
    int a;
    char* b;
};

struct Tuple getPair() {
    struct Tuple r = { 1, getString() };
    return r;
}

void foo() {
    struct Tuple t = getPair();
    printf("Integer value: %d, String: %s", t.a, t.b);
}

The structure method offers advantages in code clarity and type safety, supporting combinations of different return value types. It's important to note that when structures are large, return operations may involve memory copying, requiring consideration of performance implications.

Pointer Parameter Passing Method

Passing output values through pointer parameters represents another common strategy for multiple value returns. This approach uses pointers to directly modify variables at addresses provided by the caller, achieving the effect of "output parameters."

void getPair(int* a, char** b) {
    // Parameter validity checking
    assert(a != NULL);
    assert(b != NULL);
    
    *a = 1;
    *b = getString();
}

void foo() {
    int num;
    char* str;
    getPair(&num, &str);
    printf("Integer value: %d, String: %s", num, str);
}

The pointer method avoids the overhead of structure copying, making it particularly suitable for handling large data structures. However, special attention must be paid to pointer validity checks and memory management responsibilities.

Array Return Method

Arrays provide a concise solution when multiple values of the same type need to be returned. By passing arrays as parameters, functions can directly modify array elements to achieve multiple value returns.

void getValues(int arr[], int size) {
    if (size >= 2) {
        arr[0] = 42;  // First return value
        arr[1] = 100; // Second return value
    }
}

void foo() {
    int results[2];
    getValues(results, 2);
    printf("Result 1: %d, Result 2: %d", results[0], results[1]);
}

The array method is suitable for scenarios with homogeneous return value types, offering concise and efficient code. Ensure the array size is sufficient to accommodate all return values and maintain clear semantics for array indices.

Method Comparison and Selection Guidelines

Each method has its appropriate application scenarios: structure methods work well for returning combinations of different data types with good type safety; pointer methods excel in performance-sensitive situations, particularly when handling large data; array methods specialize in returning multiple values of the same type with the most concise implementation.

In practical development, method selection should consider: data types of return values, performance requirements, code readability, and memory management complexity. For simple numerical combinations, structure methods typically provide the most intuitive approach, while pointer methods may be more appropriate for high-performance scenarios.

Best Practices and Considerations

Regardless of the chosen method, pay attention to these key points: ensure all output parameters are properly initialized before function calls; conduct thorough parameter validity checks; define clear boundaries for memory management responsibilities; maintain consistent coding standards in team development.

Particular attention is required when using pointer methods: callers must ensure provided pointers point to valid memory regions, while functions must perform rigorous null pointer checks to avoid undefined behavior.

Conclusion

Although C doesn't directly support multiple value returns from functions, developers can flexibly achieve this functionality through mechanisms like structures, pointers, and arrays. Understanding the principles and applicable scenarios of each method helps make informed technical decisions in real projects, enabling the creation of both efficient and reliable C code.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.