Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simultaneously reassign values of two variables in c++

Is there a way in C++ of emulating this python syntax

a,b = b,(a+b)

I understand this is trivially possible with a temporary variable but am curious if it is possible without using one?

like image 495
user3235916 Avatar asked Aug 31 '25 22:08

user3235916


2 Answers

You can use the standard C++ function std::exchange like

#include <utility>

//...

a = std::exchange( b, a + b );

Here is a demonstration program

#include <iostream>
#include <utility>

int main()
{
    int a = 1;
    int b = 2;

    std::cout << "a = " << a << '\n';
    std::cout << "b = " << b << '\n';

    a = std::exchange( b, a + b );

    std::cout << "a = " << a << '\n';
    std::cout << "b = " << b << '\n';
}

The program output is

a = 1
b = 2
a = 2
b = 3

You can use this approach in a function that calculates Fibonacci numbers.

like image 191
Vlad from Moscow Avatar answered Sep 03 '25 12:09

Vlad from Moscow


You could assign to std::tie when there are more than two values to unpack. In python, you could do a, b, c = 1, 2, 3, which is not possible using std::exchange. Vlad's answer is perfect for your use case. This answer is meant to complement Vlad's answer.

int a = 1;
int b = 2;
int c = 3;

std::tie(a, b, c) = std::make_tuple(4, 5, a+b+c);
std::cout << a << " " << b << " " << c; // 4 5 6

Try it Online

like image 43
Ch3steR Avatar answered Sep 03 '25 12:09

Ch3steR