From: antispam@fricas.org   
      
   pozz wrote:   
   > After many years programming in C language, I'm always unsure if it is   
   > safer to use signed int or unsigned int.   
   >   
   > Of course there are situations where signed or unsigned is clearly   
   > better. For example, if the values could assume negative values, signed   
   > int is the only solution. If you are manipulating single bits (&, |, ^,   
   > <<, >>), unsigned ints are your friends.   
   >   
   > What about other situations? For example, what do you use for the "i"   
   > loop variable?   
   >   
   > I recently activated gcc -Wsign-conversion option on a codebase and   
   > received a lot of warnings. I started to fix them, usually expliciting   
   > casting. Is it the way or is it better to avoid the warning from the   
   > beginning, choosing the right signed or unsigned type?   
      
   I oscilated between various uses, but for PC programming I now   
   have strong preference for signed, with unsigned used when there   
   are special reasons. Basically, as long as you stay within range   
   signed agrees with mathematical integers which is normally wanted   
   semantics. Given availability of relatively cheap 64-bit integers   
   cases where you need to worry about going out of range tend to   
   be rather special. Similarly, cases where you want wraparound   
   are also rather special.   
      
   If you are going to "fix" warning by adding casts agreeing with default   
   convertions, then IMO it makes little sense. Turning off warnings   
   (possibly by using pragma if warning if imposed on you by build   
   machinery) is equally effective. You may sometimes need casts   
   which are different than default convertions, those make   
   sense. But IIUC it is basically when you want to convert   
   unsigned to bigger unsigned type. IME promoting to signed usually   
   works fine, so casts of this sort should be rare.   
      
   BTW: I tried this warning on a piece of code which intensively   
   used unsigned types (for things like device registers, etc.).   
   It produced a bunch of warnings about changed value, but all were   
   false positives: the change was intended.   
      
   I would expect that in well written code need for convertions   
   different than default promotions it relatively rare. It makes   
   some sense to turn on warnings, inspect all cases and fix   
   ones which are wrong. But having warnings on and writing   
   a lot of casts means that you loose benefits of warnings:   
   if you make a mistake writing code with casts warning will   
   not help you finding the mistake.   
      
   --   
    Waldek Hebisch   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   
|