0

When we use "return 4,5" in c++ it does not give error but instead returns 5 (at least 4 would be understandable as it should return the first number it encounters) . Why does this happen and can we use this to return 2 values in any way?

Here is the code that i tried

#include<iostream>
using namespace std;
int something()
{
    return 4,5;
}
int main()
{
    int a=0,b=0;
    a,b = something();
    cout<<a<<b<<endl;
}

also in the above code for some reason 5 is assigned to b instead of a

Humus
  • 170
  • 1
  • 3
  • 10

3 Answers3

3

This is how comma operator works - it evaluates all the operands and returns the last one.

Unfortunately, C++ does not have built-in tuple (like int, double, etc.) type, so, it is impossible to return more than one value from the function. However, you could use wrapper type std::tuple and then unpack it using std::tie function:

#include <iostream>
#include <tuple>

std::tuple<int, int> something()
{
    return {1, 2};
}

int main()
{
    int a=0, b=0;
    std::tie(a, b) = something();

    std::cout << a << b << std::endl;
}

This is a little bit overhead for two variables, though.

awesoon
  • 32,469
  • 11
  • 74
  • 99
2

It's using the built-in comma operator (since these are not user defined types). For user defined types it would be calling operator,() (the comma operator).

The comma operator evaluates both sides of the operator and returns the result of the latter. Which is why you get 5 and not 4 as the result.

As to why it is done here I cannot say - seems silly.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
1

If you want to return two values, return a std::vector with them. Maybe a std::pair, or a class. As far as why, this is just how C++ works. Comma is just an operator, like + or -. It discards its left operand and returns the right one. return returns the value of its expression from the function. The rest you can figure out yourself.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148