When to use "unsigned"? (preconditions?) 
Author Message
 When to use "unsigned"? (preconditions?)

Are there any strict rules as to when you should use unsigned?

ie. it's use in parameters _of public functions_ seems to be fraught with disaster..

eg.

        acceptPositiveInteger(unsigned anInt)
        {
                // precondition

                assert(anInt => 0,"anInt not positive");

However, I don't have a problem using it in loop indexes though..

        ie..

        unsigned monthStart;

        for (monthStart=0;monthStart<11;monthStart++) {
                do something
        }

--
                        "Mariella Mariella Mariella"
              (PGP key: send email with Subject: request pgp key)
                       (ASCII for text only messages)



Fri, 21 Feb 1997 05:30:13 GMT  
 When to use "unsigned"? (preconditions?)


   Are there any strict rules as to when you should use unsigned?
           acceptPositiveInteger(unsigned anInt)
           {
                   // precondition
                   assert(anInt => 0,"anInt not positive");
Umm, that assertion will never be false. There are no negative
values even _possible_ in the unsigned type. If you try to force
an unsigned to have a negative value, its behavior is compiler-
dependent, but most likely what will happen is that the positive
number described by the bit representation of the negative number
will be used.

I personally don't use unsigned integers that much! I think it
tends to be superstitious more than anything else. But I can say
that, for backwards traversal through arrays, I prefer to be able to do

for( int i = len-1 ; i >= 0 ; i-- ) a[i] = blah;

over

for( unsigned int i = len ; i > 0 ; ) a[--i] = blah;

Given the previous misunderstanding, I should point out that

for( unsigned int i = len-1 ; i >= 0 ; i-- ) a[i] = blah;

will not terminate.
--
Michael C. Grant           Information Systems Laboratory, Stanford University

------------------------------------------------------------------------------
"When you get right down to it, your           "Long hair, short hair---what's
average {*filter*} is really quite                 the difference once the head's
thoughtful." (David Letterman)                    blowed off?" (Nat'l Lampoon)



Fri, 21 Feb 1997 16:51:06 GMT  
 When to use "unsigned"? (preconditions?)

|> Are there any strict rules as to when you should use unsigned?

|> ie. it's use in parameters _of public functions_ seems to be fraught with disaster..

Why?

|> eg.

|>   acceptPositiveInteger(unsigned anInt)
|>   {
|>           // precondition

|>           assert(anInt => 0,"anInt not positive");

The assert is unnecessary.  An unsigned is, by definition >= 0.

I use unsigned systematically when the parameter *is* an unsigned
value, e.g.: how many somethings, or an index into a C style array.  I
use it precisely because it saves me the assert which I would
otherwise need.
--

GABI Software, Sarl., 8 rue des Francs Bourgeois, F-67000 Strasbourg, France
Conseils en informatique industrielle --
                              -- Beratung in industrieller Datenverarbeitung



Fri, 21 Feb 1997 22:46:43 GMT  
 When to use "unsigned"? (preconditions?)


Quote:
>Are there any strict rules as to when you should use unsigned?

Rarely! :-)

If int is big enough to hold all of the possible values of a variable
then you might just as well use it.

Unsigned short/int is guaranteed to be able to hold positive values
up to 65535 whereas short/int only guarantee up to 32767. There may
be the occasional time where this makes a difference.

Unsigned types are defined over a larger range of operations involving
bit operators and overflows. This mandates the use of unsigned in
some circumstances.

However there is no reason to use an unsigned type just because all the
values you are dealing with are positive. For example I wouldn't bother
in your loop code below.

Quote:
>ie. it's use in parameters _of public functions_ seems to be fraught with
> disaster..

>eg.

>        acceptPositiveInteger(unsigned anInt)
>        {
>                // precondition

>                assert(anInt => 0,"anInt not positive");

                              >= ??

I don't see any problem with this other than the assert is redundant -
you simply can't pass a negative value to this function so there is no
need to test for it.

Quote:
>However, I don't have a problem using it in loop indexes though..

>        ie..

>        unsigned monthStart;

>        for (monthStart=0;monthStart<11;monthStart++) {
>                do something
>        }

At a guess you meant:

         for (monthStart=0;monthStart<12;monthStart++) {

I wouldn't be any more inclined to declare MonthStart as unsigned than
I would as short or char which would also work here. Int is generally
safer than unsigned because you might want to perform calculations involving
monthStart later on in the code which could go negative. These would go
wrong if monthStart forced promotion to unsigned in the expression. Also
if I decide at a later date to rearrange the loop as:

        for (monthStart=11;monthStart>=0;monthStart--) {
          .
          .

it would continue to work fine with int but fail horribly with unsigned.

--
-----------------------------------------


-----------------------------------------



Fri, 21 Feb 1997 23:03:12 GMT  
 When to use "unsigned"? (preconditions?)


Quote:
>I use unsigned systematically when the parameter *is* an unsigned
>value, e.g.: how many somethings, or an index into a C style array.  I
>use it precisely because it saves me the assert which I would
>otherwise need.

I'm not convinced it saves you anything. Your function could still be called
with an int actual argument. Using an unsigned where an int would have done
doesn't avoid a potential error, it merely prevents you from being
able to test for it (unless you test whether it is > INT_MAX). You might just
as well use an int argument and not test that. It is possible that your
application uses positive values that will fit in an unsigned but not in
an int but that's not particularly common (except maybe under DOS where
an unsigned can hold a full segment offset).

--
-----------------------------------------


-----------------------------------------



Sat, 22 Feb 1997 18:56:54 GMT  
 When to use "unsigned"? (preconditions?)

Quote:

> An important use of unsigned is when you need large numbers. The largest
> unsigned number is twice the size of the largest signed number, which
> can sometimes be a good reason to use unsigned.

If you need large numbers, you had better use the type that comes next
in the list char, short, int, long. Or if their ranges are not large
enough, use double or long double. The more important reason to use
unsigned types is that they don't cause undefined behaviour when they
overflow. All IMHO of course :-)

--
                                       ^^

University of Twente                 =x=  \        tel. +31 53 893747
Tele-Informatics & Open Systems        |   \       tfx. +31 53 333815
P.O. Box 217   7500 AE Enschede       /|__  \
The Netherlands                      (____)_/

An age is called Dark not because the light fails to shine, but because
people refuse to see it.
                -- James Michener, "Space"



Sun, 23 Feb 1997 01:35:39 GMT  
 When to use "unsigned"? (preconditions?)


Quote:
: Papanagnou) writes:


: |> >for( unsigned int i = len-1 ; i >= 0 ; i-- ) a[i] = blah;

: |> >will not terminate.

: |> I consider this loop as the one and greatest problem using unsigned.
: |> The compiler (and run time system) gives no hints.

: Not even a warning?  I would expect a compiler to give a warning for
: such a test, given that it can never be false.

Gcc saies: warning: unsigned value >= 0 is always 1
--
A.  B <=> True                    B.  A <=> False




Sun, 23 Feb 1997 16:16:34 GMT  
 When to use "unsigned"? (preconditions?)


Quote:
>>for( unsigned int i = len-1 ; i >= 0 ; i-- ) a[i] = blah;

>>will not terminate.

>I consider this loop as the one and greatest problem using unsigned.
>The compiler (and run time system) gives no hints.

Comparing an unsigned type as >= constant 0 is something the compiler
certainly *could* diagnose (and a reasonable optimiser should anyway) and
would be a useful diagnostic. However it could be a warning which is only
generated when optimisation in the compiler is enabled (which is why
you often need to enable full optimisation to get full diagnostics on
a compiler).

--
-----------------------------------------


-----------------------------------------



Sun, 23 Feb 1997 19:36:26 GMT  
 When to use "unsigned"? (preconditions?)

Quote:


>   Are there any strict rules as to when you should use unsigned?
>       acceptPositiveInteger(unsigned anInt)
>       {
>               // precondition
>               assert(anInt => 0,"anInt not positive");
>Umm, that assertion will never be false. There are no negative
>values even _possible_ in the unsigned type. If you try to force
> [...]

Lengths of (physical, mathematical) objects are best expressed by
unsigned ints.  They cannot become negative !
String length, for example, or sizes of memory arrays.

Example:
Declaring every length of a string in a string class unsigned, shows
the range of the arguments by the declaration.  No further comments
have to be made, no assertions to test negative values have to be
formulated.  The interface becomes clearer.

Quote:
>for( unsigned int i = len-1 ; i >= 0 ; i-- ) a[i] = blah;
>will not terminate.

I consider this loop as the one and greatest problem using unsigned.
The compiler (and run time system) gives no hints.

Quote:
>--
>Michael C. Grant           Information Systems Laboratory, Stanford University


Janis
--



Sat, 22 Feb 1997 16:35:45 GMT  
 When to use "unsigned"? (preconditions?)

Quote:
Papanagnou) writes:


|> >for( unsigned int i = len-1 ; i >= 0 ; i-- ) a[i] = blah;

|> >will not terminate.

|> I consider this loop as the one and greatest problem using unsigned.
|> The compiler (and run time system) gives no hints.

Not even a warning?  I would expect a compiler to give a warning for
such a test, given that it can never be false.
--

GABI Software, Sarl., 8 rue des Francs Bourgeois, F-67000 Strasbourg, France
Conseils en informatique industrielle --
                              -- Beratung in industrieller Datenverarbeitung



Sat, 22 Feb 1997 21:51:44 GMT  
 When to use "unsigned"? (preconditions?)




   Papanagnou) writes:

   |> >for( unsigned int i = len-1 ; i >= 0 ; i-- ) a[i] = blah;
   |> >will not terminate.
   |> I consider this loop as the one and greatest problem using unsigned.
   |> The compiler (and run time system) gives no hints.
   Not even a warning?  I would expect a compiler to give a warning for
   such a test, given that it can never be false.

I think some compilers will indeed warn you about it, at least with
full warnings on!

--
Michael C. Grant           Information Systems Laboratory, Stanford University

------------------------------------------------------------------------------
"When you get right down to it, your           "Long hair, short hair---what's
average {*filter*} is really quite                 the difference once the head's
thoughtful." (David Letterman)                    blowed off?" (Nat'l Lampoon)



Sat, 22 Feb 1997 23:29:08 GMT  
 When to use "unsigned"? (preconditions?)
An important use of unsigned is when you need large numbers. The largest
unsigned number is twice the size of the largest signed number, which
can sometimes be a good reason to use unsigned.

--Eric



Sat, 22 Feb 1997 19:30:50 GMT  
 When to use "unsigned"? (preconditions?)

Quote:



>>>for( unsigned int i = len-1 ; i >= 0 ; i-- ) a[i] = blah;

>>>will not terminate.

>>I consider this loop as the one and greatest problem using unsigned.
>>The compiler (and run time system) gives no hints.
>Comparing an unsigned type as >= constant 0 is something the compiler
>certainly *could* diagnose (and a reasonable optimiser should anyway) and
>would be a useful diagnostic. However it could be a warning which is only
>generated when optimisation in the compiler is enabled (which is why
>you often need to enable full optimisation to get full diagnostics on
>a compiler).

I agree.
You have to consider a generalization, too, when the condition contains
no constants, as in the inner loop

  for (unsigned int k = n; k >= 0; k--)
    for (unsigned int i = n; i >= k; i--)
      ...;

You cannot *expect* that every compiler detects that.  That's a problem.

--



Mon, 24 Feb 1997 17:49:57 GMT  
 When to use "unsigned"? (preconditions?)

Quote:
(Fergus Henderson) writes:




|> >|> Are there any strict rules as to when you should use unsigned?

|> >|> ie. it's use in parameters _of public functions_ seems to be fraught with disaster..

|> >Why?

|> Because the compiler won't check if you pass a negative value.

It won't even let you pass a negative value.  There is no such thing
as a negative unsigned value.

|> >|> eg.

|> >|>         acceptPositiveInteger(unsigned anInt)
|> >|>         {
|> >|>                 // precondition
|> >
|> >|>                 assert(anInt => 0,"anInt not positive");
|> >
|> >The assert is unnecessary.  An unsigned is, by definition >= 0.

|> Yes, that's exactly why the use of unsigned is "fraught with disaster"!

|> >I use unsigned systematically when the parameter *is* an unsigned
|> >value, e.g.: how many somethings, or an index into a C style array.  I
|> >use it precisely because it saves me the assert which I would
|> >otherwise need.

|> I think you've missed the point.  It actually doesn't remove the
|> requirement to check the precondition, it just removes any possibility
|> of actually fulfilling this requirement.

Yes and no.  I regularly check *both* bounds.  Passing an unsigned
means that I only have to check one.  And the C standard is so written
that if the user actually does try to pass a negative value, the value
the compile will actually pass will violate the upper bound on any
conforming implementation.  (Either that, or the range of values was
to big to be passed as an int anyway.)  So I do save one half of the
assert.

That isn't the real reason, of course.  The declared interface is part
of the program documentation; I expect that anyone calling my function
will have looked at the header file.  If I declare a parameter
unsigned, I no more expect a -3 than I do 2.7.  (And of course, there
is no way once in the program to trap the fact that I was actually
passed 2.7.)  If I request an int, then I must document the fact that
it must not be negative, and add a check for the case in my code.
Being by nature lazy...

Oh, and just to make one point clear.  The actual difference is
minimal.  The added test/comment are not really that much to worry
about.  So if you feel better passing an int, I'm not going to say
that you are wrong.
--

GABI Software, Sarl., 8 rue des Francs Bourgeois, F-67000 Strasbourg, France
Conseils en informatique industrielle --
                              -- Beratung in industrieller Datenverarbeitung



Mon, 24 Feb 1997 22:21:31 GMT  
 When to use "unsigned"? (preconditions?)

Quote:


>|> Are there any strict rules as to when you should use unsigned?

>|> ie. it's use in parameters _of public functions_ seems to be fraught with disaster..

>Why?

Because the compiler won't check if you pass a negative value.

Quote:
>|> eg.

>|>       acceptPositiveInteger(unsigned anInt)
>|>       {
>|>               // precondition

>|>               assert(anInt => 0,"anInt not positive");

>The assert is unnecessary.  An unsigned is, by definition >= 0.

Yes, that's exactly why the use of unsigned is "fraught with disaster"!

Quote:
>I use unsigned systematically when the parameter *is* an unsigned
>value, e.g.: how many somethings, or an index into a C style array.  I
>use it precisely because it saves me the assert which I would
>otherwise need.

I think you've missed the point.  It actually doesn't remove the
requirement to check the precondition, it just removes any possibility
of actually fulfilling this requirement.

--



Mon, 24 Feb 1997 02:24:20 GMT  
 
 [ 22 post ]  Go to page: [1] [2]

 Relevant Pages 

1. What is "unsigned char data[0];"

2. Hash tables with "unsigned long" keys

3. "Double to 2 Unsigned Longs"

4. Converting from "unsigned __int64" to double

5. WHEN TO USE "UNSIGNED"? (PRECONDI

6. On using "using"

7. remove() vrs fopen("""w")

8. Displaying binary data as ascii "1"'s and "0"'s

9. Looking for "Shroud"/"Obfus"

10. ""help with TSR""

11. Parse trees and "("")"

12. How to convert "unsigned long" to "struct in_addr"???

 

 
Powered by phpBB® Forum Software