0

I have some code with lines which increment a counter.

++ count;

Sometimes I have an if condition which means I should increment count by 2.

count += 2;

Does "double increment'ing" work in the same way?

++ ++ count;

It would be helpful to know if both C and C++ compilers interpret this the same way.

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225

2 Answers2

7

As this is clearly syntactically correct, the question that remains is: "Is this UB because of unsequenced writes?"

It is not (in C++11 and later) because

5) The side effect of the built-in pre-increment and pre-decrement operators is sequenced before its value computation (implicit rule due to definition as compound assignment)

(From here)

So the code is fine as of C++11.

However, the sequencing rules were different before that, and pre-C++11, the code actually has UB.

In C, that code does not even compile.

The fact that the behavior is different between C and C++ and even between different C++ standards and that this question arises in the first place is a hint that the simple count += 2; is the safer and more readable version. You should prefer it over the "cute and clever" ++ ++count;.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
0

There are two methods. One that obviously works, one where you have to ask a question on StackOverflow. There are comments saying "in C++ 11 or later"... How sure are you that your C++ code runs with C++ 11 and not something older? Even if you use extensions that were not part of an earlier language, your language could be C++0x with some extensions.

Clearly you shouldn't care whether the second method works or not, but use the one that obviously works.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • Compatibility with an older version of the standard cannot be a reason not to use a feature. Otherwise no new features would be used. But you have other valid points. – too honest for this site Mar 08 '16 at 14:32
  • @Olaf The thing is, there is UB, which the compiler will most likely not warn you about. With most other features, you get either a compiler error, or well defined behaviour. – juanchopanza Mar 08 '16 at 15:58
  • @juanchopanza: I still wounder why this is allowed anyway. Which lvalue does the "outer" `++` increment as side-effect? – too honest for this site Mar 08 '16 at 16:01
  • @Olaf I guess the same as the inner one? Pre-increment yields an lvalue (at least in C++) – juanchopanza Mar 08 '16 at 16:06
  • @juanchopanza: Ok, so there is another difference. It does not in C. So, that intermediate lvalue is incremented then and just dropped, I suppose? Makes the construct look even more obscure to me. Anyway, thanks for the infos. – too honest for this site Mar 08 '16 at 16:08