voiddiv(inta,intb,int*quotient,int*remai"/> voiddiv(inta,intb,int*quotient,int*remai">

Home  >  Article  >  Backend Development  >  How to return multiple values ​​from a function in C/C++?

How to return multiple values ​​from a function in C/C++?

王林
王林forward
2023-09-04 12:09:06983browse

How to return multiple values ​​from a function in C/C++?

In C or C, we cannot directly return multiple values ​​from a function. In this section, we will see how to return multiple values ​​from a function using some tricks.

We can use the "call by address" method to return multiple values ​​from a function, or "call by reference". In the calling function we will use two variables to store the result 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 returns the quotient and remainder from a function after dividing two numbers.

Sample 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

The above is the detailed content of How to return multiple values ​​from a function in C/C++?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete