1

I have been working with C++ for many years, but just realized something fishy about incremental assignment.

I have this snippet

  a = 4; 
  b = 2;
  c = 0;
  c = c + a > b; printf("a: %d\tb: %d\tc: %d\n",a,b,c);
  c = c + a > b; printf("a: %d\tb: %d\tc: %d\n",a,b,c);
  c +=    a < b; printf("a: %d\tb: %d\tc: %d\n",a,b,c);
  c +=    a > b; printf("a: %d\tb: %d\tc: %d\n",a,b,c);
  c +=    a > b; printf("a: %d\tb: %d\tc: %d\n",a,b,c);

And the result is

a: 4    b: 2    c: 1
a: 4    b: 2    c: 1
a: 4    b: 2    c: 1
a: 4    b: 2    c: 2
a: 4    b: 2    c: 3

If you note, the first two lines are the same. Or 'c' doesn't get updated after the first c = c + a > b; However, the value of c gets updated when we use the incremental assignment +=

Any thoughts?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Sriram Murali
  • 5,804
  • 2
  • 26
  • 32
  • 4
    What do you *imagine* should happen? Everything is exactly as it should be. – Kerrek SB Sep 23 '11 at 17:26
  • This falls under "ugly" code: The '>` operator is not an arithmetic operator so it should NOT be used in an arithmetic statement or expression. This was a hack from long ago when boolean types and operators were not available (in ancient languages). – Thomas Matthews Sep 23 '11 at 19:33

3 Answers3

7

< has lower precedence than +.

c = c + a > b; is interpreted as c = (c + a) > b;

It is just so, there doesn't need to be a reason, but if there was one, it might be that people more often compare arithmetic expressions than use the results of comparisons in arithmetic expressions..

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
2

In the first line, c + a > b is true, which converts to 1, so the first line reads c = 1;. Rinse and repeat.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
1

The compiler interprets your code as c = (c + a) > b where you probably want it to be interpreted as c = c + (a > b).

Stefan Werner
  • 440
  • 2
  • 7