3

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.

Diggi55
  • 174
  • 8

5 Answers5

4

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

(a--,b--);
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
3
// 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);
}
QuentinUK
  • 2,997
  • 21
  • 20
2

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)

DasElias
  • 569
  • 8
  • 19
1

You can do like :

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

Output: 43

NixoN
  • 661
  • 1
  • 6
  • 19
1

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

Mohit
  • 1,185
  • 2
  • 11
  • 25