[Libreoffice] signed/unsigned comparison (was: [PATCH] Replace SvULongs with vector and code clean up part 1)

Lubos Lunak l.lunak at suse.cz
Tue Aug 9 06:02:18 PDT 2011

On Tuesday 09 of August 2011, Stephan Bergmann wrote:
> On Aug 6, 2011, at 3:32 PM, Maciej Rumianowski wrote:
> >> @@ -1325,7 +1288,7 @@ String
> >> SvxNumberFormatShell::GetComment4Entry(short nEntry) if(nEntry < 0)
> >>         return String();
> >>
> >> -    if(nEntry<aCurEntryList.Count())
> >> +    if(nEntry < (short)aCurEntryList.size())
> >>     {
> >
> > 5. Should short type be replaced with sal_Int16 or more appropriate type?
> Some C++ compilers warn about comparisons like (x < y) where x is an rvalue
> of a signed integral type and y is an rvalue of an unsigned integral type. 
> And, in general, they are right in doing so:  Assume that x is an rvalue -1
> of type int and y is some rvalue of type unsigned int.  Usual arithmetic
> conversion causes the int -1 to be converted to unsigned int. Undefined
> behavior, hard-disk erased.  Oops.


> However, if the programmer can prove that x is always non-negative in the
> above comparison, there is usually an easy solution to that problem:

[skipped a description of the typical OOo style of using a sledge hammer to 
punch in a nail that's anything but easy and can potentially cause almost as 
much trouble as it solves]

 Actually a much better solution to the problem is to realize that 'unsigned' 
belongs together with other legacy stuff and is just not worth it, perhaps 
except for bitfields (which are kind of legacy stuff these days as well).

 If the extra bit of value is really needed, then it's usually much better to 
go for a larger type (as 'unsigned' does not mean it has any magic range 
checks included), otherwise just going with plain 'int' simply does the job. 
Too bad usage of STL drags in these problems, but that's not a problem that 
couldn't be solved. Certainly much easier than having code cluttered with 
checks and casts that serve no real purpose.

 Lubos Lunak
 l.lunak at suse.cz

More information about the LibreOffice mailing list