473,883 Members | 1,570 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

efficiency concern: when to really use unsigned ints and when not to

Hello,

Often I happen to be dealing with nonnegative integers and since I know I won't
need negative numbers here I declare them as unsigned simply to make the program
somewhat clearer. Effectively, though, signed integers would often work too since
unless I am doing some modular arithmetic modulo the word length then I almost
never need to use the high bit since the integers I deal with are usually not
that large, and I would assume this is true of most programs in general.

So, the question is, when you know an integer is not going to be negative, is that
good enough reason to declare it as unsigned, or does doing so somewhat slow down
the computer (e.g. are signed addition, subtraction, etc... somewhat faster and
why would that be so?)?

Thanks,

Neil
Nov 14 '05
49 5926


Dan Pop wrote:

[snip}


How many times have you defined an object occupying half of your address
space or more?

Dan


It may be rare for others, but I work with an in-memory database
which uses over 2.5 GB of 4GB available memory.

We're moving to a 64-bit machine to get around the limitation,
too.

--
Ñ
"It is impossible to make anything foolproof because fools are so
ingenious" - A. Bloch

Nov 14 '05 #41
Jack Klein wrote:
On 5 Feb 2004 13:18:31 -0800, nz******@cs.mun .ca (Neil Zanella) wrote
(snip)
So, the question is, when you know an integer is not going to be negative, is that
good enough reason to declare it as unsigned, or does doing so somewhat slow down
the computer (e.g. are signed addition, subtraction, etc... somewhat faster and
why would that be so?)?

Speed or efficiency of operation is no different between pure signed
or unsigned types on any architecture developed in the last quarter
century at least.


ESA/390, which is much less than 25 years old, didn't have unsigned
divide or multiply, but the more recent z/Architecture does.

There might be others more recent, or otherwise still running
that don't have unsigned multiply and divide of the appropriate
width. If you are only doing add/subtract/relational/index
operations on the values then I don't see any reason not to
use unsigned.

I don't know all the architectures to know, but multiply and
divide are the ones I would look for first.

-- glen

Nov 14 '05 #42
Dan Pop wrote:
In <b6************ **************@ posting.google. com> nz******@cs.mun .ca (Neil Zanella) writes:
(snip regarding when to use unsigned integers)
Signed integers and unsigned integers are fairly different beasts,
intended for different purposes. Avoid unsigned integers unless you need
their special semantics (or the additional range), even if you're only
manipulating positive values. After all, the prototype of main() isn't int main(unsigned argc, char **argv); despite the fact that argc is not supposed to have negative values. If it's intended for usual arithmetic operations, use signed integer.
If it's intended for bit manipulation operations and/or modulo arithmetic,
use unsigned integer.
Despite what I am about to say, I agree 100% with these statements.
(With the possible exception of modulo arithmetic not modulo
a power of two.)
Avoid as much as possible mixing the two flavours in the same
expression, because very nasty bugs may arise. The fact that size_t is unsigned is a real pain in the ass, because this
type is seldom used in a genuine unsigned context. It should have been
signed, for the same reason that argc is signed.
Well, yes. Except that there are cases where size_t values might
be between INT_MAX and UINT_MAX, which could cause problems.
(Assuming that the implementation does it right for those values.)

argc > INT_MAX should be pretty rare.

(snip)
Speed is not a concern. On two's complement architectures, the two are
usually handled identically. It's the intended purpose of the variable
that dictates the choice (again, unless you need the extra range provided
by the unsigned flavour, but this doesn't seem to be the case).


Well, for multiply and divide they are different, and it isn't so easy
to do unsigned divide using a signed divide operation. There are still
machines around without unsigned multiply and divide.

-- glen

Nov 14 '05 #43
In <vo************ *************** *****@4ax.com> Mark McIntyre <ma**********@s pamcop.net> writes:
On Tue, 10 Feb 2004 17:21:31 GMT, in comp.lang.c , CBFalconer
<cb********@ya hoo.com> wrote:
Dan Pop wrote:
CBFalconer <cb********@yah oo.com> writes:
> Dan Pop wrote:
>>
>> The fact that size_t is unsigned is a real pain in the ass, because
>> this type is seldom used in a genuine unsigned context. It should
>> have been signed, for the same reason that argc is signed.
>
>There are two fundamental problems without compatible resolution.
>First, int to unsigned conversion is always possible, while the
>reverse may not be. This encourages the use of ints. Secondly,
>size_t usually represents things that can be addressed in the
>system, and this is very unlikely to waste any bit positions.
>This more or less mandates the use of size_t (and thus unsigned)
>in many places.

How many times have you defined an object occupying half of your
address space or more?


Quite often. Of course it wasn't in C, and it didn't have large
virtual memory.


FWIW in the olden days, when 512K was standard on Amstrad PCs, I did find
myself allocating 256K in one go. Hardly a truly enormous object when you
think about it.


And hardly a problem for a hypothetically signed size_t that could
cover objects up to 2 GB, but you were not supposed to be able to
understand that...

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #44
On Tue, 10 Feb 2004 22:35:14 +0000, in comp.lang.c , Christian Bau
<ch***********@ cbau.freeserve. co.uk> wrote:
In article <c0**********@s unnews.cern.ch> , Da*****@cern.ch (Dan Pop)
wrote:
In <40************ ***@yahoo.com> CBFalconer <cb********@yah oo.com> writes:
>Dan Pop wrote:
>>
>> The fact that size_t is unsigned is a real pain in the ass, because
>> this type is seldom used in a genuine unsigned context. It should
>> have been signed, for the same reason that argc is signed.
>
>There are two fundamental problems without compatible resolution.
>First, int to unsigned conversion is always possible, while the
>reverse may not be. This encourages the use of ints. Secondly,
>size_t usually represents things that can be addressed in the
>system, and this is very unlikely to waste any bit positions.
>This more or less mandates the use of size_t (and thus unsigned)
>in many places.


How many times have you defined an object occupying half of your address
space or more?


And if you have done so, did you run into problems because ptrdiff_t is
not capable of representing differences between pointers in all cases?


when your memory space is 512Kb or less, this is not an issue.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 14 '05 #45
In article <gf************ *************** *****@4ax.com>,
Mark McIntyre <ma**********@s pamcop.net> wrote:
On Tue, 10 Feb 2004 22:35:14 +0000, in comp.lang.c , Christian Bau
<ch***********@ cbau.freeserve. co.uk> wrote:
In article <c0**********@s unnews.cern.ch> , Da*****@cern.ch (Dan Pop)
wrote:
In <40************ ***@yahoo.com> CBFalconer <cb********@yah oo.com> writes:

>Dan Pop wrote:
>>
>> The fact that size_t is unsigned is a real pain in the ass, because
>> this type is seldom used in a genuine unsigned context. It should
>> have been signed, for the same reason that argc is signed.
>
>There are two fundamental problems without compatible resolution.
>First, int to unsigned conversion is always possible, while the
>reverse may not be. This encourages the use of ints. Secondly,
>size_t usually represents things that can be addressed in the
>system, and this is very unlikely to waste any bit positions.
>This more or less mandates the use of size_t (and thus unsigned)
>in many places.

How many times have you defined an object occupying half of your address
space or more?


And if you have done so, did you run into problems because ptrdiff_t is
not capable of representing differences between pointers in all cases?


when your memory space is 512Kb or less, this is not an issue.


Usually ptrdiff_t covers exactly half the range as size_t, because
ptrdiff_t is signed and size_t is unsigned. If you use more than half of
the capacity of size_t for a single object, then you are in trouble.

Apparently you meant "half of available memory", not "half of the amount
of memory that can be specified by size_t".
Nov 14 '05 #46
> So, the question is, when you know an integer is not going to be negative, is that
good enough reason to declare it as unsigned


Yes.

Several critical security vulnerabilites have been discovered in the
last year or so that have been caused by integer manipulation issues.
These have occurred not only in Microsoft software(the latest ASN.1
critical vulnerability is one example), but in several open source
software packages and closed source packages from other vendors.

The contents of this thread suggests that, even amongst experienced C
programmers, there is still a disturbing lack of awareness of this
issue.

If you have any doubt on the seriousness of integer manipulation bugs
follow this link:
http://www.google.com/search?q=integer+overflow

I suggest every C\C++ programmer starts by reading these articles:
http://msdn.microsoft.com/library/en...re04102003.asp
http://msdn.microsoft.com/library/en...re09112003.asp

As an exercise consider the additional checks that need to be taken in
the check() function below. How many would be removed by making a and
b unsigned?

int check(signed int a, signed int b)
{
/* a and b are considered untrusted numbers. */

if (a + b < 50)
return 1;
else
return 0;
}

void somefunc(void)
{
/* a_cnt, b_cnt, a_str, b_str from somewhere */
char buf[50];

if (!check(a_cnt, b_cnt) return;

strncpy(buf, a_str, a_cnt);
strncpy(buf, b_str, b_cnt);
}

--
NOTE: My email address is invalid. Please post as reply.
Nov 14 '05 #47
On 12 Feb 2004, anony*mouse wrote:
I suggest every C\C++ programmer starts by reading these articles:
http://msdn.microsoft.com/library/en...re04102003.asp
http://msdn.microsoft.com/library/en...re09112003.asp


Uh, that doesn't look like "C\C++" at all, which is more like
SmallTalk ;)

Nov 14 '05 #48
anony*mouse wrote:
.... snip ...
As an exercise consider the additional checks that need to be
taken in the check() function below. How many would be removed
by making a and b unsigned?

int check(signed int a, signed int b)
{
/* a and b are considered untrusted numbers. */
if ((a < 0) || (b < 0)) return 0; if (a + b < 50)
return 1;
else
return 0;
}


The above suffices for any system which has integer overflow
detection. Now consider the ugly tests required if a and b are
unsigned, so that overflow of a + b cannot occur.

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 14 '05 #49
On Mon, 16 Feb 2004 20:12:59 GMT
CBFalconer <cb********@yah oo.com> wrote:
anony*mouse wrote:
... snip ...

As an exercise consider the additional checks that need to be
taken in the check() function below. How many would be removed
by making a and b unsigned?

int check(signed int a, signed int b)
{
/* a and b are considered untrusted numbers. */

if ((a < 0) || (b < 0)) return 0;
if (a + b < 50)
return 1;
else
return 0;
}


The above suffices for any system which has integer overflow
detection. Now consider the ugly tests required if a and b are
unsigned, so that overflow of a + b cannot occur.


int check(unsigned int a, unsigned int b)
{
/* a and b are considered untrusted numbers. */
/* no check for < 0 as now using unsigned int which, by definition, is= 0. */


if ((a < 50) && (b < 50) && (a + b < 50))
return 1;
else
return 0;
}

Doesn't look very ugly to me and with short circuit evaluation the
addition is only done if both a and b are less than 50 and so
guaranteed not to overflow. Admittedly, ugliness is in the eye of the
beholder.
--
Flash Gordon
Paid to be a Geek & a Senior Software Developer
Although my email address says spam, it is real and I read it.
Nov 14 '05 #50

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

Similar topics

9
7029
by: Ton den Hartog | last post by:
I am confused, when use ID and when use NAME to identify an element in HTML ? Ton den Hartog -- Computer museum tonh: http://www.tonh.net - 10.000 visitors !! GGGallery website generator: http://www.tonh.net/gggallery
10
10831
by: bg_ie | last post by:
Hi, I have a function which compares two unsigned ints and returns their difference in order to establish which is the greater of the two. int Compare(unsigned int time_left, unsigned int time_right) { return (time_left - time_right); }
0
9932
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
11109
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
10728
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...
1
10833
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9558
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
7959
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
5782
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4602
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
4200
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.