How can we return multiple values from a function in C/C++?


In C or C++, we cannot return multiple values from a function directly. In this section, we will see how to use some trick to return more than one value from a function.

We can return more than one values from a function by using the method called “call by address”, or call by reference. In the invoker function, we will use two variables to store the results, and the function will take pointer type data. So we have to pass the address of the data.

In this example, we will see how to define a function that can return quotient and remainder after dividing two numbers from one single function.

Example Code

#include<stdio.h>
void div(int a, int b, int *quotient, int *remainder) {
   *quotient = a / b;
   *remainder = a % b;
}
main() {
   int a = 76, b = 10;
   int q, r;
   div(a, b, &q, &r);
   printf("Quotient is: %d\nRemainder is: %d\n", q, r);
}

Output

Quotient is: 7
Remainder is: 6

Updated on: 04-Oct-2023

24K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements