Search code examples
pythonc++variable-assignmentswap

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?


Solution

  • 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.