Multiple Return Values in C

Our program demonstrates the concept of multiple return values. While C doesn’t have built-in support for multiple return values like some modern languages, we can achieve similar functionality using pointers or structures. Here’s an example implementation:

#include <stdio.h>

// We use a struct to return multiple values
struct Values {
    int a;
    int b;
};

// This function returns a struct containing two integers
struct Values vals() {
    struct Values result = {3, 7};
    return result;
}

int main() {
    // We call the function and store the result in a struct
    struct Values result = vals();
    printf("%d\n", result.a);
    printf("%d\n", result.b);

    // If we only want one value, we can just ignore the other
    struct Values result2 = vals();
    printf("%d\n", result2.b);

    return 0;
}

In this C implementation:

  1. We define a struct Values to hold multiple return values.

  2. The vals() function returns an instance of struct Values containing two integers.

  3. In the main() function, we call vals() and access the returned values through the struct members.

  4. To demonstrate ignoring one of the values (similar to the blank identifier _ in some languages), we simply don’t use result2.a.

To compile and run this program:

$ gcc multiple_return_values.c -o multiple_return_values
$ ./multiple_return_values
3
7
7

While C doesn’t have native support for multiple return values, using structures or pointers allows us to return multiple values from a function in a clean and organized manner.