0

I was wondering why the ++ operator is defined over bool... however when I tried the --operator, it was not defined for bool..

Can someone please explain me the reason behind that?

David Hoelzer
  • 15,862
  • 4
  • 48
  • 67
hims
  • 325
  • 3
  • 10

2 Answers2

2

Refer to the documentation: https://msdn.microsoft.com/en-us/library/tf4dy80a.aspx

When a postfix or prefix ++ operator is applied to a variable of type bool, the variable is set to true. The postfix or prefix -- operator cannot be applied to a variable of this type.

Jerry
  • 4,258
  • 3
  • 31
  • 58
  • 2
    This answer does not address the question: Why? – Lii May 11 '15 at 11:57
  • 2
    @Lii In a sense it does... "You can't" because the documentation says you can't. :) – David Hoelzer May 11 '15 at 11:58
  • @DavidHoelzer, Jerry: Those are true statements but they don't answer the question! Why was the language designed this way? – Lii May 11 '15 at 12:03
  • @Lii You can ask the "designer" – Jerry May 11 '15 at 12:03
  • @Lii Write to Bjarne and ask him. Though, honestly, it does make sense. If I increment false, it will become true. If I decrement, however, am I making something more false?? Or, how do I evaluate true? Non-zero? Are sub-zero values false? – David Hoelzer May 11 '15 at 12:13
  • 1
    @Lii Probably from when `false==0`, and `true!=0`. Which gives us (using integers) `++false==true`, `++true==true`. And then the surprising results `--false==true`, and most suprising `--true=={true or false}`. – Richard Critten May 11 '15 at 12:18
  • These are real attempts to answers! Similar things are put forward in [the question of which this one is a duplicate](http://stackoverflow.com/questions/3450420/bool-operator-and). – Lii May 11 '15 at 12:46
2

From the Standard 5.2.6.1

The value of the operand object is modified by adding 1 to it, unless the object is of type bool, in which case it is set to true. [ Note: this use is deprecated, see Annex D. —end note ]

And 5.2.6.2 emphasis mine

The operand of postfix -- is decremented analogously to the postfix ++ operator, except that the operand shall not be of type bool. [ Note: For prefix increment and decrement, see 5.3.2. —end note ]

And Annex D

D.1 Increment operator with bool operand [depr.incr.bool] 1 The use of an operand of type bool with the ++ operator is deprecated (see 5.3.2 and 5.2.6).

So in turn the reason you can't is because it is against the standard.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402