TheKian
TheKian

Reputation: 39

How to separate 2 values returned by a function into 2 different variables C++

The function that return the values is this

float calcVelocity(float xacceleration, float yacceleration,sf::Clock clock, float originalDistance){
    sf::Time time = clock.getElapsedTime(); //get current time and store in variable called time
    float xvelocity = xacceleration*time.asSeconds();
    float yvelocity = yacceleration*time.asSeconds();
    while (!(originalDistance + calcDisplacement(yacceleration, clock, originalDistance) <= 0)) {
        time = clock.getElapsedTime(); //get current time and store in variable called time
        xvelocity = xacceleration*time.asSeconds();//Calculates velocity from acceleration and time
        yvelocity = yacceleration*time.asSeconds();
        cout << xvelocity<<endl;//print velocity
        cout << yvelocity << endl;
        system("cls");//clear console
    }
    return xvelocity;
    return yvelocity;
}

I then want them to print as finalXvelocity = blah and finalYvelocity = blah after the while loop is finised. In the main code when I call the function and output the result, it prints both values together. E.g finalXvelocity = blahblah.

I was thinking I could separate the values returned into the main code and then print them using those but I don't know how to do that.

Thanks

Upvotes: 1

Views: 86

Answers (2)

cwschmidt
cwschmidt

Reputation: 1204

If you have more than one return value, since C++11 you can return them as a std::tuple. No need to explicit declare a data struct.

e.g.

tuple<float,float> calcVelocity(/*parameters*/) {
  // your code
  return make_tuple(xvelocity,yvelocity);
}

Outside the function you can access the values by:

tuple mytuple = calcVelocity(/*parameters*/);
float xvelocity = get<0>(my_tuple);
float yvelocity = get<1>(my_tuple);

For pre-C++11 std::pair is also an option for just 2 values. But in this case the struct solution is more explicit.

Upvotes: 4

Bathsheba
Bathsheba

Reputation: 234715

Use a struct:

struct velocity
{
    float x_component; /*ToDo - do you really need a float*/
    float y_component;
};

This will be the most extensible option. You can extend to provide a constructor and other niceties such as computing the speed. Perhaps a class is more natural, where the data members are private by default.

Upvotes: 5

Related Questions