home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 32,630 of 33,346   
   =?ISO-8859-15?Q?Daniel_Kr=FCgler?= to Exactly. The specification   
   Re: Useful applications for boolean incr   
   02 Nov 12 14:11:13   
   
   From: daniel.kruegler@googlemail.com   
      
   Am 02.11.2012 19:31, schrieb Stuart:   
      
   > I can only imagine one reason why someone would want to use   
   > operator++ on a bool variable, which would be that he wants to   
   > negate the value in a single line:   
   >   
   > bool negate (bool value) {   
   >   return ++value;   
   > }   
      
   Yes, but that doesn't do what you expect, right?   
      
   > Apparently operator++ does not work like this   
      
   Exactly. The specification says that the result of increment on any   
   bool value is true.   
      
   > (it seems to invoke operator++ on the internal representation of a   
   > bool):   
      
   Not really, the result is specified to be true - that's it. You can   
   consider it as equivalent to converting 1 (the successor of false) or   
   2 (the successor of true) back to bool.   
      
   > The only use case for operator++ on bool I could think of was the   
   > following:   
   >   
   > #include    
   > #include    
   >   
   > void print(const std::vector& vec) {   
   >     bool needComma = false;   
   >     for (auto it = vec.begin(); it != vec.end(); ++it) {   
   >         if (needComma++)   
   >             std::cout << ", ";   
   >         std::cout << *it;   
   >     }   
   > }   
   >   
   > int main () {   
   >     std::vector v;   
   >     v.push_back(1);   
   >     v.push_back(2);   
   >     v.push_back(3);   
   >     print(v);   
   > }   
   >   
   > Admittedly, this is a bit far-fetched will probably yield wrong   
   > results for large vectors if bool is implemented using 8bit values.   
      
   No, the outcome is independent of representation. It will always be   
   true after the first incrementation. Otherwise the result of n   
   incrementations would be dependent on the representation. The   
   specification requires that the following program would present an   
   infinite loop:   
      
   int main () {   
         bool v = false;   
         while (++v) {}   
   }   
      
   Thanks for your feedback,   
      
   Daniel Krügler   
      
      
      
   --   
         [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
         [ comp.lang.c++.moderated.    First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca