473,855 Members | 2,150 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
26 36102

Gavin Deane wrote:

<snip>
Personally, I do not accept that argument for unsigned as documentation
to mean "negative values make no sense here". The variable name (age,
buffer_size, radius) serves that purpose.


<snip>

Hmmm.... Not sure why I'd want an integer, signed or otherwise, for a
radius. That would be a floating point type. Replace that with a more
sensible quantity - number of clients connected to the server, or
number of pigs on the farm or something.

Gavin Deane

Feb 22 '06 #21
On 2006-02-21, Alf P. Steinbach <al***@start.no > wrote:
* 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.


That will help when the domain doesn't include all positive
representable integers, yes. You assumed a domain restriction that was
not in evidence. ;-)
With a signed argument the test might go like

assert( age >= 0 ); // signed validity test.
assert( age < 200 ); // more signed validity test.
I much prefer your second example, but perhaps that's a matter of
taste. Moreover, I don't want or need to learn the rules for unsigned
arithmetic if I only use them for their bit-values.
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.


Yes, I should have been more specific.

--
Neil Cerutti
Feb 22 '06 #22
On 2006-02-22, Ben Pope <be************ ***@gmail.com> wrote:
Daniel T. wrote:
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 > > Surely overflow and underflow are a problem
with both signed and unsigned?


These are often situations where you are unable to check validity
without domain specific knowledge - I don't see how signed unsigned
vary in that regard.


Because a signed negative value will be silently converted to a
positive unsigned value. I suppose this works both ways, though. I
can't prevent someone from passing a positive unsigned value to my
signed function, yielding the same problem in the mirror.

--
Neil Cerutti
Feb 22 '06 #23
On Wed, 22 Feb 2006 10:34:20 +0000, Ben Pope
<be************ ***@gmail.com> wrote:
Daniel T. wrote:
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


Surely overflow and underflow are a problem with both signed and unsigned?


They are a problem with signed (undefined or non-portable behavior),
but behavior with unsigned is well-defined by the standard (values
wrap). There is never any true overflow with unsigned integral values.
These are often situations where you are unable to check validity
without domain specific knowledge - I don't see how signed unsigned vary
in that regard.

Ben Pope


--
Bob Hairgrove
No**********@Ho me.com
Feb 22 '06 #24
Bob Hairgrove wrote:
On Wed, 22 Feb 2006 10:34:20 +0000, Ben Pope
<be************ ***@gmail.com> wrote:
Surely overflow and underflow are a problem with both signed and unsigned?


They are a problem with signed (undefined or non-portable behavior),
but behavior with unsigned is well-defined by the standard (values
wrap). There is never any true overflow with unsigned integral values.


I guess that depends on your definition of overflow, in the context
provided I would class the following as overflow (on a platform with 8
bit char):

#include <iostream>

int main() {
unsigned char val = 128;
val *= 2; // overflow
std::cout << static_cast<uns igned int>(val) << "\n";
val = 0;
val -= 1; // underflow?
std::cout << static_cast<uns igned int>(val);
}

The behaviour may well be defined, but but I would call it overflow,
nonetheless.

I'm not sure if underflow is the correct term for the second "problem",
but that's what I call it.

Ben Pope
--
I'm not just a number. To many, I'm known as a string...
Feb 22 '06 #25

"Neil Cerutti" <le*******@emai l.com> skrev i meddelandet
news:sl******** *************@F IAD06.norwich.e du...
On 2006-02-22, Ben Pope <be************ ***@gmail.com> wrote:
Daniel T. wrote:
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 > > Surely overflow and underflow are a
problem
with both signed and unsigned?


These are often situations where you are unable to check validity
without domain specific knowledge - I don't see how signed unsigned
vary in that regard.


Because a signed negative value will be silently converted to a
positive unsigned value. I suppose this works both ways, though. I
can't prevent someone from passing a positive unsigned value to my
signed function, yielding the same problem in the mirror.


So the real problem is mixing signed and unsigned values. :-)

One solution, recommended elsewhere in this thread, is to just use one
kind. Probably signed then.
Bo Persson
Feb 22 '06 #26

"Ben Pope" <be************ ***@gmail.com> skrev i meddelandet
news:43******** **************@ taz.nntpserver. com...
Bob Hairgrove wrote:
On Wed, 22 Feb 2006 10:34:20 +0000, Ben Pope
<be************ ***@gmail.com> wrote:
Surely overflow and underflow are a problem with both signed and
unsigned?


They are a problem with signed (undefined or non-portable
behavior),
but behavior with unsigned is well-defined by the standard (values
wrap). There is never any true overflow with unsigned integral
values.


I guess that depends on your definition of overflow


In this context the difference is that with unsigned values you get a
known (but possibly useless) result. With signed artihmetic, you get
the dreaded "undefined behavior" - making your entire program formally
unusable.
Bo Persson
Feb 22 '06 #27

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

Similar topics

19
6488
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
31519
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
4965
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
4183
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
15681
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
5377
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
3320
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
5054
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
6469
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
2680
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
9903
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
10692
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10375
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
9526
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
7927
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
7084
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();...
0
5953
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4168
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3194
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.