Home > Blockchain >  Simultaneously reassign values of two variables in c
Simultaneously reassign values of two variables in c

Time:01-29

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?

CodePudding user response:

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.

CodePudding user response:

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

  •  Tags:  
  • Related