473,785 Members | 2,428 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

signed vs unsigned

LuB
This isn't a C++ question per se ... but rather, I'm posting this bcs I
want the answer from a C++ language perspective. Hope that makes sense.

I was reading Peter van der Linden's "Expert C Programming: Deep C
Secrets" and came across the following statement:

"Avoid unnecessary complexity by minimizing your use of unsigned types.
Specifically, don't use an unsigned type to represent a quantity just
because it will never be negative (e.g., "age" or "national_debt" )."

Admittedly, I minimize comments in my code. I use them when necessary
but try to limit them to one or two lines. I just don't like their
aesthetic affect in the source. I find the code much harder to read
littered with paragraphs of explanations.

I find the code easier to read when broken up with appropriate newlines
and small, short comments acting as headings.

So - that effectually means that I try my darndest to write
self-describing code. Shorter functions, self-explanatory names for
functions and variable names, etc. Sometimes exceessive commenting is
necessary, but as a whole, I tend to avoid it.

I'm really enjoying Peter's book, but I find this comment hard to
swallow considering that if an age or array index can never be negative
- I would want to illustrate that with an apporpriate choice of type -
namely, unsigned int.

Am I in the minority here? Is my predilection considered poor style?

I guess, from the compiler's standpoint ... using int everywhere is
more portable ... since comparison's against unsigned int can vary
between K&R and ANSI C.

I'm not incurring some type of performance penalty for such decisions
am I?

Thanks in advance,

-Luther

Feb 21 '06 #1
26 36088
On 21 Feb 2006 08:58:23 -0800, "LuB" <lu*********@ya hoo.com> wrote:
I'm really enjoying Peter's book, but I find this comment hard to
swallow considering that if an age or array index can never be negative
- I would want to illustrate that with an apporpriate choice of type -
namely, unsigned int.

Am I in the minority here?
Hopefully not!
Is my predilection considered poor style?


Absolutely not!

The key to dealing with signed vs. unsigned is not to mix them, if
possible, in comparisons. Be especially wary of comparing an unsigned
counter value to 0 while decrementing the counter.

--
Bob Hairgrove
No**********@Ho me.com
Feb 21 '06 #2
Like you said, marking a type as "unsigned" if for nothing else is an
easy documentation for other developers that it will never be negative.
I havn't read his stuff but I can't imagine what complexities he is
talking about.

Performance differences depend largly on your architecture. On AMD64,
division/modulus are faster when using unsigned types. Conversion to
floating point is faster with signed types. Addition/subtraction are
the same.

Feb 21 '06 #3

LuB wrote:
I'm really enjoying Peter's book, but I find this comment hard to
swallow considering that if an age or array index can never be negative
- I would want to illustrate that with an apporpriate choice of type -
namely, unsigned int.


The only reason that I can think of that you might want to not use
'unsigned' is if the assumption that it will never be negative might
change. However, most times you are better off with the assumption and
the protection of the unsigned type and then change it later if you
have to. Minimize dependencies on the type so that it is easier to do.

The great thing about unsigned is if the value can't be negative and
you use signed then you always have to check it. Simply defining the
type as unsigned gets rid of all that as well as documenting your
domain.

Feb 21 '06 #4
LuB posted:
This isn't a C++ question per se ... but rather, I'm posting this bcs I
want the answer from a C++ language perspective. Hope that makes sense.

I was reading Peter van der Linden's "Expert C Programming: Deep C
Secrets" and came across the following statement:

"Avoid unnecessary complexity by minimizing your use of unsigned types.
Specifically, don't use an unsigned type to represent a quantity just
because it will never be negative (e.g., "age" or "national_debt" )."

Admittedly, I minimize comments in my code. I use them when necessary
but try to limit them to one or two lines. I just don't like their
aesthetic affect in the source. I find the code much harder to read
littered with paragraphs of explanations.

I find the code easier to read when broken up with appropriate newlines
and small, short comments acting as headings.

So - that effectually means that I try my darndest to write
self-describing code. Shorter functions, self-explanatory names for
functions and variable names, etc. Sometimes exceessive commenting is
necessary, but as a whole, I tend to avoid it.

I'm really enjoying Peter's book, but I find this comment hard to
swallow considering that if an age or array index can never be negative
- I would want to illustrate that with an apporpriate choice of type -
namely, unsigned int.

Am I in the minority here? Is my predilection considered poor style?

I guess, from the compiler's standpoint ... using int everywhere is
more portable ... since comparison's against unsigned int can vary
between K&R and ANSI C.

I'm not incurring some type of performance penalty for such decisions
am I?

Thanks in advance,

-Luther

My first rule is to write "const" wherever I can.
(except for return types).

My second rule is to write "unsigned" wherever I can.
Thus I'll write:

unsigned GetDogAge(unsig ned const age)
{
return age * 7;
}

Or alternatively re-use the parameter variable:

unsigned GetDogAge(unsig ned age)
{
return age *= 7;
}
-Tomás
Feb 21 '06 #5
In article <11************ **********@f14g 2000cwb.googleg roups.com>,
ro**********@gm ail.com wrote:
The great thing about unsigned is if the value can't be negative and
you use signed then you always have to check it. Simply defining the
type as unsigned gets rid of all that as well as documenting your
domain.


And the bad thing about unsigned is that if code would otherwise make
the value negative, you can't check it. IE

void foo( unsigned s ) {
// at this point s == 4294966272
// is it an error (s came in as -1024) or
// does the client really want us to deal with that number?
}

Bjarne Stroustrup says, "The unsigned integer types are ideal for uses
that treat storage as a bit array. Using an unsigned instead of an int
to gain one more bit to represent positive integers is almost never a
good idea. Attempts to ensure that some values are positive by declaring
variables unsigned will typically be defeated by the implicit conversion
rules."

--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Feb 21 '06 #6

Tomás wrote:
Or alternatively re-use the parameter variable:

unsigned GetDogAge(unsig ned age)
{
return age *= 7;
}


Performs an unnecissary and unused assignment as age is automatic and
will be gone after return.

Feb 21 '06 #7

LuB wrote:
This isn't a C++ question per se ... but rather, I'm posting this bcs I
want the answer from a C++ language perspective. Hope that makes sense.

I was reading Peter van der Linden's "Expert C Programming: Deep C
Secrets" and came across the following statement:

"Avoid unnecessary complexity by minimizing your use of unsigned types.
Specifically, don't use an unsigned type to represent a quantity just
because it will never be negative (e.g., "age" or "national_debt" )."
<snip> -Luther


Well, it is a style issue, so many people will probably disagree with
me. They are probably all right, and I would still be able to respect
them :)

That said, I personally use signed types almost all the time, even if
something should never be negative. Every once in a while, I make a
horribly stupid error in something like a file loading function.
Suppose an object can have zero or more child objects. If my loader
returns an object that claims to have -1024 children, then I know I've
done something wrong, and it can be easier to track down bugs that
compile and don't crash. If it just claims that there are a large
positive number of children, it's not as easy to catch the error
condition. There is even the wildly unlikely possibility that there is
an error due to a hardware fault like bad RAM. (Though, the problems
are almost always caused by me! Many people who are better programmers
than me may find that hardware accounts for a greater percentage of
problems than I do :)

Also, I use negative values as intentional error codes and special
cases. Some people consider this horrible style. I can respect that.
But, for a lot of the things I do, it is the quickest, easiest,
simplest, and clearest way to have a recoverable error. So, my
hypothetical object loading function might return an object which
claims -1 children if it failed to open the file, -2 if it failed to
parse the file, -3 if the file contained invalid information, etc. I
know, exceptions are probably better for most of these things, but my
personal style is to write C++ that looks a lot like C, and uses
occasional C++ features. It's just more inline with the way I think
about the problems.

Also, by always using signed types, I can avoid comparisons between
signed and unsigned. It is also generally easier to catch overflow.
After all, the national debt might never be negative, but it certainly
might exceed MAX_INT on some systems! :)

I tend to work alone on personal projects. So, the most important
thing for me is that my personal coding style is readable - to me.
Feel free to strongly disagree with my style.

Feb 21 '06 #8
On 2006-02-21, Tomás <NU**@NULL.NULL > wrote:
My first rule is to write "const" wherever I can.
(except for return types).

My second rule is to write "unsigned" wherever I can.
I don't agree with that rule.
Thus I'll write:

unsigned GetDogAge(unsig ned const age)
{
return age * 7;
}


What do you expect to happen if a client passes in an negative int?

The argument is not in the domain, yet the error has been rendered
impossible to detect or recover from.

--
Neil Cerutti
Feb 21 '06 #9
* Neil Cerutti:
On 2006-02-21, Tomás <NU**@NULL.NULL > wrote:
My first rule is to write "const" wherever I can.
(except for return types).

My second rule is to write "unsigned" wherever I can.


I don't agree with that rule.
Thus I'll write:

unsigned GetDogAge(unsig ned const age)
{
return age * 7;
}


What do you expect to happen if a client passes in an negative int?

The argument is not in the domain, yet the error has been rendered
impossible to detect or recover from.


I don't disagree with your viewpoint regarding using or not using
unsigned whenever possible; I think both are valid viewpoints, and as
with indentation the main thing is to be consistent in one's choices.

However, I disagree with your reason!

With the unsigned argument a validity test might go like

assert( age < 200 ); // unsigned validity test.

With a signed argument the test might go like

assert( age >= 0 ); // signed validity test.
assert( age < 200 ); // more signed validity test.

Now, first of all that demonstrates the "impossible to detect" is simply
incorrect, and second, in my view it demonstrates a slight superiority
for unsigned in this particular case, with respect to validity testing.

Cheers,

- Alf

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Feb 21 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
6481
by: MiniDisc_2k2 | last post by:
Okay, here's a question about the standard. What does it say about unsigned/signed mismatches in a comparison statement: char a = 3; unsigned char b = 255; if (a<b) Now what's the real answer here? If a is converted to unsigned, then b>a. But, if b is converted to signed,then a>b. What's the correct coversion (what is the compiler supposed to do?)
3
31511
by: Siemel Naran | last post by:
Hi. Is there a way to convert the type signed int to the type unsigned int, char to unsigned char, signed char to unsigned char, and so on for all the fundamental integer types? Something like template <> struct to_unsigned<signed int> : public std::unary_function<signed int, unsigned int> { unsigned int operator()(signed int x) const { return x; } };
9
4960
by: Fred Ma | last post by:
Hello, I've been trying to clear up a confusion about integer promotions during expression evaluation. I've checked the C FAQ and C++ FAQ (they are different languages, but I was hoping one would clear up the confusion), as well as googling groups and the web. The confusion is that for a binary operator,
9
4178
by: dam_fool_2003 | last post by:
For int data type the default range starts from signed to unsigned. If we don't want negative value we can force an unsigned value. The same goes for long also. But I don't understand why we have signed char which is -256. Does it means that we can assign the same ASCII value to both signed and unsigned. That means the ASCII value can be represented with a type of signed char and also unsigned char? For example int main(void) {
10
15664
by: tinesan | last post by:
Hello fellow C programmers, I'm just learning to program with C, and I'm wondering what the difference between signed and unsigned char is. To me there seems to be no difference, and the standard doesn't even care what a normal char is (because signed and unsigned have equal behavior). For example if someone does this: unsigned char a = -2; /* or = 254 */
20
5365
by: Hanzac Chen | last post by:
Hi, I don't understand why this could happen? The Code 1 will output `fff9' and the Code 2 will output `1' How could the `mod 8' not have effect? /* Code 1 */ #include <stdio.h> #include <stdlib.h>
10
3310
by: =?iso-8859-2?B?SmFuIFJpbmdvuQ==?= | last post by:
Hello everybody, this is my first post to a newsgroup at all. I would like to get some feedback on one proposal I am thinking about: --- begin of proposal --- Proposal to add signed/unsigned modifier to class declarations to next revision of C++ programming language
7
5049
by: somenath | last post by:
Hi All, I am trying to undestand "Type Conversions" from K&R book.I am not able to understand the bellow mentioned text "Conversion rules are more complicated when unsigned operands are involved. The problem is that comparisons between signed and unsigned values are machine- dependent, because they depend on the sizes of the various integer types. For example, suppose that int is 16 bits
6
6458
by: Kislay | last post by:
Consider the following code snippet unsigned int i=10; int j= - 2; // minus 2 if(i>j) cout<<"i is greater"; else cout<<"j is greater"; Since i is unsigned , j is greater . I know why , but vaguely . Can
39
2667
by: Juha Nieminen | last post by:
I was once taught that if some integral value can never have negative values, it's a good style to use an 'unsigned' type for that: It's informative, self-documenting, and you are not wasting half of the value range for values which you will never be using. I agreed with this, and started to always use 'unsigned' whenever negative values wouldn't make any sense. I did this for years. However, I slowly changed my mind: Doing this often...
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10325
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8972
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6740
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4053
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3646
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.