Reputation: 9
i have to write a code that has a function that takes two integers and returns x as (a + b) and y as (a * b) and when i run it, it only outputs y. Why doesnt it output (or return) x?
#include <iostream>
using namespace std;
int math (int a, int b) {
int x, y;
x = a + b;
y = a * b;
return x, y;
}
int main() {
cout << math (5,3);
getchar();
getchar();
return 0;
}
Upvotes: 0
Views: 91
Reputation: 153929
There are two ways to make a function return more than one value. The first is to use out parameters, either references or pointers:
void
math( int a, int b, int& sum, int& product )
{
sum = a + b;
product = a * b;
}
int
main()
{
int s;
int p;
math(5, 3, s, p);
std::cout << s << ' ' << p << std::endl;
return 0;
}
The other is to define a class to contain the two values:
struct MathResults
{
int sum;
int product;
};
MathResults
math( int a, int b )
{
return MathResults{ a + b, a * b };
}
std::ostream&
operator<<( std::ostream& dest, MathResults const& value )
{
dest << value.sum << ' ' << value.product;
}
int
main()
{
std::cout << math( 5, 3 ) << std::endl;
return 0;
}
In most cases, the second solution is to be preferred.
Upvotes: 0
Reputation: 2359
You can only return one thing. You can put those in a struct, and return it. Simpler example.
struct xy {
int x;
int y;
};
xy math(int a, int b) {
xy pair;
int x, y;
pair.x = a + b;
pair.y = a * b;
return pair;
}
Upvotes: 0
Reputation: 500377
The return type of math
is int
, so this is what it returns (a single integer).
The expression x, y
uses the comma operator. The comma operator evaluates x
, discards its value, and then evaluates and returns y
. In other words, return x, y
is equivalent to return y
.
You could use std::pair<int,int>
to return a pair of integers.
Upvotes: 3
Reputation: 136
The line
return x, y;
does not do what you expect. The comma operator returns only the value after the last comma - in this case, y
. To return multiple values, you should use a struct
or class containing both.
Upvotes: 1