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 31,923 of 33,346   
   =?ISO-8859-1?Q?Daniel_Kr=FCgler?= to All   
   Re: unsigned type assigned a signed type   
   14 Feb 12 02:38:00   
   
   5bd92d8f   
   From: daniel.kruegler@googlemail.com   
      
   Am 13.02.2012 19:35, schrieb Brad Tilley:   
   > I saw some code that does this and wondered why. Why would someone   
   > wish to place a signed value in an unsigned type? I was surprised the   
   > compiler did not issue a warning. If this is valid, what would be the   
   > reason for doing it?   
   >   
   > #include   
   > #include   
   >   
   > int main()   
   > {   
   >     boost::uint64_t i = -9151314442815602945;   
   >     std::cout<<  i<<  std::endl;   
   >   
   >     unsigned int j = -327681234;   
   >     std::cout<<  j<<  std::endl;   
   >   
   >     return 0;   
   > }   
      
   This conversion is especially useful, if you want to view at the integer as a   
   set of bits, thus performing some bit operations on the value.   
      
   But you are right that this is actually some very special use-case and it   
   would be sufficient to require an explicit cast for this.   
      
   Nonetheless these integer conversions have a long tradition in C (which is the   
   main root of C++), therefore the implicit conversion. If you have a C++11   
   compiler and if you use braces for initialization, you should get a narrowing   
   compiler error:   
      
   boost::uint64_t i = {-9151314442815602945}; // Error, narrowing conversion   
   unsigned int j = {-327681234}; // Error, narrowing conversion   
      
   HTH & Greetings from Bremen,   
      
   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