Humus Humus - 8 months ago 43
C++ Question

What does return a,b do and why?

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

using namespace std;
int something()
return 4,5;
int main()
int a=0,b=0;
a,b = something();

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


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.