1

Is there a way of using the compound assignment operator to achieve something like this:

a = (a * 10) + b;

Initially I tried the following:

a *= 10 + b;

but this is equivalent to:

a = a * (10 + b)

Just curious. Ran across this today. This is not homework.

Cole W
  • 15,123
  • 6
  • 51
  • 85

2 Answers2

6

If you really need to make sure a is evaluated only once, you could use the fact that *= returns lvalue:

(a *= 10) += b;

but it's hardly good code, and I think it might be invoking undefined behaviour prior to C++11 due to modifying a twice (once in *= and once in +=) without intervening sequence points.

Wolf
  • 9,679
  • 7
  • 62
  • 108
Cubbi
  • 46,567
  • 13
  • 103
  • 169
  • @EdHeal I'm not. This was purely because I was interested if you could do it or not. – Cole W Dec 16 '11 at 12:48
  • I doubt that *`'a' is evaluated only once`* – Wolf Mar 29 '17 at 09:31
  • I at first thought: Is there really a good chance for UB in compilers before C++11? I took me a while to find http://stackoverflow.com/a/10654019/2932052 – Wolf Mar 29 '17 at 10:03
0

https://ideone.com/WWudo

#include <iostream>

using namespace std;

int main() 
{
        int a = 5;
        int b = 10;
        (a *= b) += 10;
        cout << a;
        return 0;
}

Outputs 60.

Lee Louviere
  • 5,162
  • 30
  • 54