How to decrement several variables in C++in a single line statement?

Viewed 164

Edit: I replaced the phrase 'in one line' by 'in a single line statement' since this is what I was looking for

Let's say we have the following variables at hand:

int a = 5;
int b = 9;

Is there a way to compress this ...

a--;
b--;

... into in a single line statement?? The question is not about decrementing multiple variables in a for loop, since this seems to be a common yet unrelated question.

5 Answers

You probably mean "in a single statement", not just "in a single line". Then you can use the comma-operator:

(a--,b--);
// use a template
template<class ... Args>
void decr(Args& ... args){
    (... , --args);
}

decr(a,b,c);

// or, in C++20, auto
void decr(auto& ... args){
    (... , --args);
}

You could just write the statements in one single line, like this :

a--, b--;

(thanks to @Aziz for the improvement with the comma instead of the semicolon)

You can do like :

int a = 5;
int b = 4;
(a -= 1), (b -= 1);
std::cout << a << b;

Output: 43

You can try something like :

#include <iostream>

using namespace std;

    main ()
    {
      int a = 5, b = 9;
      a--, b--;
      cout << a;
      cout << b;        
      return 0;
    }

Output: 48

Related