How can I return multiple values from a function in C?
Tags: functions, multiplereturn, cprogramming, returnmultiplevalues
Published: 2023-04-03 09:44:51

Hello everyone, my name is Anil Das and I have worked as a Software Engineer at Luxoft India. As a programmer, I often use functions in my daily programs to make the code more modular and reusable. Sometimes, I need to return multiple values from a function, and it can be a bit tricky to accomplish this in C. That's why I would like to share my knowledge and experience on this topic with you today. In this article, I will discuss various techniques and approaches that you can use to return multiple values from a function in C programming. So, let's dive into the details and explore this topic further.

In programming, functions are one of the most important constructs for building modular and reusable code. A function is a block of code that performs a specific task and can be called multiple times within a program. In C, functions are defined using the syntax:

```
return_type function_name(parameter_list) {
    // function body
}
```

The return_type is the data type of the value that the function returns. The function_name is a unique identifier for the function, and the parameter_list is a comma-separated list of variables that the function takes as input.

In C, a function can only return one value. However, there are several ways to return multiple values from a function. In this article, we will explore some of these techniques and provide code examples to demonstrate how they work.

## Using Pointers
One way to return multiple values from a function in C is to use pointers. A pointer is a variable that stores the memory address of another variable. By passing pointers as function arguments, we can modify the values of variables outside the function scope. Here's an example:

```
void get_two_values(int *a, int *b) {
    *a = 10;
    *b = 20;
}

int main() {
    int x, y;
    get_two_values(&x, &y);
    printf("%d %d", x, y);
    return 0;
}
```
In this example, we define a function called get_two_values that takes two integer pointers as input. Inside the function, we set the values of a and b to 10 and 20, respectively. We then call the function from main and pass the addresses of x and y using the & operator. After the function call, the values of x and y are updated to 10 and 20, respectively, and we print them using printf.

This technique works well for small numbers of values, but it can quickly become difficult when we need to return many values. Additionally, it can be error-prone if we forget to pass the correct number or type of pointers to the function.

## Using Arrays
Another way to return multiple values from a function in C is to use arrays. An array is a collection of variables of the same data type that are stored in contiguous memory locations. By returning an array from a function, we can encapsulate multiple values into a single variable. Here's an example:

```
int* get_three_values() {
    static int arr[3] = {10, 20, 30};
    return arr;
}

int main() {
    int* vals = get_three_values();
    printf("%d %d %d", vals[0], vals[1], vals[2]);
    return 0;
}
```
In this example, we define a function called get_three_values that returns a pointer to an array of three integers. Inside the function, we define a static array arr with the values 10, 20, and 30. We then return a pointer to arr.

In main, we call get_three_values and assign the returned pointer to vals. We then access the elements of the array using the square bracket notation and print them using printf.

This technique works well for returning a fixed number of values, but it can be inflexible if we need to return a variable number of values. Additionally, it can be error-prone if we forget to allocate enough memory for the returned array.

## Using Structs
A more flexible way to return multiple values from a function in C is to use structs. A struct is a user-defined data type that can encapsulate multiple variables of different data types into a single unit. By returning a struct from a function, we can group related values together and easily access them using dot notation. Here's an example:

```
struct values {
    int a;
    int b;
    int c;
};

struct values get_three_values() {
    struct values v = {10, 20, 30};
    return v;
}

int main() {
    struct values vals = get_three_values();
    printf("%d %d %d", vals.a, vals.b, vals.c);
    return 0;
}
```
In this example, we define a struct called values that contains three integer variables a, b, and c. We then define a function called get_three_values that returns a values struct. Inside the function, we create a local values struct v and set its values to 10, 20, and 30. We then return v.

In main, we call get_three_values and assign the returned values struct to vals. We can then access the values of the struct using the dot notation and print them using printf.

This technique is flexible and allows us to return a variable number of values of different data types. However, it can be memory-intensive if we need to return large structs, and it requires us to define a new struct for each set of values that we want to return.

## Using Unions
Another way to return multiple values from a function in C is to use unions. A union is a user-defined data type that can store multiple variables of different data types, but only one variable can be accessed at a time. By returning a union from a function, we can store different types of values in the same variable and choose which value to access based on the context. Here's an example:

```
union values {
    int a;
    float b;
    char c;
};

union values get_value(char type) {
    union values v;
    switch (type) {
        case 'i':
            v.a = 10;
            break;
        case 'f':
            v.b = 3.14;
            break;
        case 'c':
            v.c = 'A';
            break;
    }
    return v;
}

int main() {
    union values val = get_value('i');
    printf("%d\n", val.a);
    val = get_value('f');
    printf("%f\n", val.b);
    val = get_value('c');
    printf("%c\n", val.c);
    return 0;
}
```

In this example, we define a union called values that can store an integer a, a float b, or a char c. We then define a function called get_value that takes a character type as input and returns a values union. Inside the function, we create a local values union v and set its value based on the input type. We then return v.

In main, we call get_value three times with different input types and assign the returned values union to val. We can then access the value of val based on its type using the dot notation and print it using printf.

This technique is useful for returning values of different data types that are related but not always used together. However, it can be confusing if we forget which value is currently stored in the union. Therefore, we need to keep track of the type of value stored in the union to access it correctly.

## Conclusion
In conclusion, there are several ways to return multiple values from a function in C, including using arrays, structures, unions, and pointers. Each method has its advantages and disadvantages, depending on the situation.

Arrays are useful when we need to return a fixed number of values of the same data type. Structures and unions are useful when we need to return values of different data types that are related. Pointers are useful when we need to modify the values of variables indirectly.

When using structures, unions, or pointers to return multiple values, we need to be careful when accessing their values to avoid errors. We should also keep track of the types of values stored in structures and unions to access them correctly.

Overall, returning multiple values from a function is an important feature of C programming that can make our code more efficient and readable. By using the appropriate method for our specific needs, we can write better programs that are easier to maintain and debug.