Search code examples
c++returntuples

Issue returning multiple values with a tuple for a function


Hi I was just having a few issues with a function I made to return multiple values after looking around for ways to return two values from a function, however I still seem to be getting errors from this function. I was using this website as a reference: https://en.cppreference.com/w/cpp/utility/tuple and am running the default (latest version of c++17).

#include <tuple>
std::tuple<int, int> returnCoordinates() 
{
  int xCoordinate = -2;
  int yCoordinate = 2;
  return {xCoordinate, yCoordinate}; //can only do in c++ 17 
}

int main()
{
  int xCoordinate;
  int yCoordinate;
  auto[xCoordinate, yCoordinate] = returnCoordinates(); //only works c++17
  return 0;
}

The error I'm getting is "expression must have a constant value the value of xCoordinate cannot be declared as a constant" and I'm not exactly sure why. Edit: As suggested by a commenter I removed the declaration of xCoordinate and yCoordinate, but it now seems to be saying that xCoordinate and yCoordinate are undefined. However, if I switch out this line of code:

auto[xCoordinate, yCoordinate] = returnCoordinates(); //only works c++17

with this:

std::tie(xCoordinate, yCoordinate) = returnCoordinates();

it seems to work, I'm just confused about why this is, apologies for any misunderstanding on my part.


Solution

  • Thanks to the commenters M.M and NathanOliver, I managed to figure out what was wrong. First of all, I removed my initial declaration of:

    int xCoordinate;
    int yCoordinate;
    

    as:

     auto[xCoordinate, yCoordinate] = returnCoordinates(); //only works c++17
    

    declares new variables.

    Also, I wasn't using the latest c++ compiler. To change that go to project-> properties -> C/C++ -> Language -> C++ Language Standard -> Preview - Features from the Latest C++ Working Draft(/std::c++latest) The default setting for this means that an error will pop up for the following code: However, otherwise this code now works:

    #include <tuple>
    std::tuple<int, int> returnCoordinates() 
    {
      int xCoordinate = -2;
      int yCoordinate = 2;
      return {xCoordinate, yCoordinate}; //can only do in c++ 17 
    }
    
    int main()
    {
      auto[xCoordinate, yCoordinate] = returnCoordinates(); //only works c++17
      return 0;
    }