-2

why incase of boolean, overflow doesn't occur in circular fashion. eg say a=126 when you reach 128 and you increment it, a goes to -127 if range is -127 to 128. similarly for boolean it is 0 to 1 so it should move around 0101010101 and so on. please clarify

using namespace std; 

int main() 
{ 

bool a; 

for (a = 1; a <= 5; a++) 
    cout << a; 

return 0; 
} 
NightOx
  • 9
  • 4
  • 3
    Please clarify what? Overflowing is UB. The compiler is allowed to reformat your harddisk if you overflow a bool and still be adherent to the C++ specification. – Botje Sep 02 '20 at 07:29
  • 1
    Overflow is a machine limit, not a language specification. Overflow occurs when you are adding into an addressed area more bits than it can contain. The minimum addressable memory is 8 bits, and there is no reason why adding 1 to a boolean it will overflows – Christian Vincenzo Traina Sep 02 '20 at 07:31
  • I am not getting is the mechanism of overflow for boolean different that int,char data types? – NightOx Sep 02 '20 at 07:33
  • @ShubhamNayak there is no mechanism of overflow. In older C++ (pre C++17), no matter what is the value of `a`, `a++` will set it to `true`. In C++17 and newer it will simply not compile. – Yksisarvinen Sep 02 '20 at 07:40

1 Answers1

5

From cppreference

If the operand of the pre-increment operator is of type bool, it is set to true

If the operand of the post-increment operator is of type bool, it is set to true

Note that this behaviour was removed in C++17 and your code won't compile with newer standards (probably because it was confusing).

Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
  • 1
    Precisely. The only reason that incrementing a bool is still there is for historical compatibility with C – bremen_matt Sep 02 '20 at 07:33
  • @bremen_matt -- C doesn't have `bool`; there is no C compatibility issue. Having `bool` increments saturate was a clever idea introduced when C++ was first being standardized and, like most clever ideas, it turned out to be more confusing than useful. – Pete Becker Sep 02 '20 at 14:53
  • I tried to write a quick comment and it backfired. My understanding is that in C, one idiom was to create an int to indicate, "something was initialized". If the int was zero, then you would run your initialization and increment the int. When c++ gave us a bool, then to be backwards compativale with this idiom, they let bools be incremented. And the closest behavior to the C idiom was to say that the result of incrementing a bool always yields true. – bremen_matt Sep 02 '20 at 19:16