0

I am trying to write a function in c++ to calculate the sum and product so my code is like that:

#include <iostream>
using namespace std; 
int Product_Sum(int x, int y, int z)
{
int sum, product;
sum = x + y + z;
product = x * y * z;

return sum, product;
}

int main() {
int result;
int x = 5, y = 10, z = 15;
result = Product_Sum(x, y, z);

cout << result;
enter code here

}

as a result I am just getting the sum of the numbers, how I can return both values together ? I tried writing it with retrurning 0 but I think it's not the right way

Emad
  • 1
  • 1
  • 3
    Does this answer your question? [Returning multiple values from a C++ function](https://stackoverflow.com/questions/321068/returning-multiple-values-from-a-c-function) – Rob Streeting Jun 01 '21 at 09:41
  • `std::pair` or dedicated struct. – Jarod42 Jun 01 '21 at 09:43
  • 1
    you can only return one value, but you can return a value of type `struct product_and_sum { int product; int value; };` – 463035818_is_not_an_ai Jun 01 '21 at 09:43
  • 1
    fwiw, you should initialize variables already when you declare them, ie `int sum = x + y + z;` rather than `int sum; sum = x+y+z;`. Uninitialized variables can easily lead to hard to detect bugs (undefined behavior) and it is much harder to make such mistakes when you write `int sum = x+y+z;` – 463035818_is_not_an_ai Jun 01 '21 at 09:46
  • Instead of returning you can have additional parameters passed by reference ie `bool Product_Sum(int x, int y, int z, someStructContainingMultipleResults & result)` and the bool return type can be used to indicate successful execution vs error cases ie divide by zero, usage can be now `if(Product_Sum(....) ) {//do something useful}` – saumitra mallick Jun 01 '21 at 10:06
  • @saumitramallick: I would avoid output parameters. You have `std::optional`/exception (and proposals for `std::expected` or equivalent) to handle error. – Jarod42 Jun 02 '21 at 10:04

0 Answers0