Change values of x and y (c++)

Home / Uncategorized / Change values of x and y (c++)

Question:
How can I change the values of x and y in this code?

When I try to do it by x=y, y=x; it changes it to the same numbers.

How can I do this?

How can I do this for 3 values like (x y z)?
#include
using namespace std;
int main()
{
int x=4;
int y=6;
cout<
using namespace std;
int main()
{
int x=4;
int y=6;
x=y,y=x;
cout< Answer:
This is because you first set x’s value and then copy that value into y. There is a standard library function called std::swap, which should do the job.

You can see an exapmle of it here.

std::swap is defined in the header before C++11 and in since C++11. So make sure you #include the correct header.

The benefit of using std::swap in C++11 as opposed to having a third temporary variable that you copy the value into, is that std::swap uses std::move and thereby creates no additional copies.

For three numbers you’ll have to make your own implementation like this:#include

int main() {
int x{5}, y{3}, z{2};

int temp{std::move(x)};
x = y;
y = z;
z = temp;

std::cout << x << ' ' << y << ' ' << z << 'n'; return 0; } Ideone Read more

Leave a Reply

Your email address will not be published. Required fields are marked *