473,807 Members | 2,763 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

comparison signed vs unsigned

Hi all,

When should I be worried about doing a comparison of signed vs unsigned
ints? Could someone give me a example where such a comparison would lead to
unwanted results?

Thanks,
Tim.
May 6 '06
18 9459
On Sat, 06 May 2006 13:44:03 +0200, "Alf P. Steinbach"
<al***@start.no > wrote:
* Olaf van der Spek:
On Sat, 06 May 2006 12:29:41 +0200, Rolf Magnus <ra******@t-online.de>
wrote:
Timothee Groleau wrote:

Hi all,

When should I be worried about doing a comparison of signed vs unsigned
ints? Could someone give me a example where such a comparison would lead
to unwanted results?
#include <iostream>

int main()
{
int a = -100;
unsigned int b = 100;
std::cout << a << " is "
<< (a < b ? "" : "not") << " less than " << b << '\n';
}


What's the rationale for doing an unsigned comparion instead of a
signed comparison in case of mixed arguments?


Integer promotion comes into play. That's primarily designed for
assignment, promoting to types with ever widening range of values that
can be represented. 'unsigned' can /represent/ all 'int' values (you
can convert from 'int' to 'unsigned' with well-defined unique result)
but not vice versa.


Why is unsigned int -> int not well-defined?
And I disagree, unsigned(-1) may have the same bit pattern but doesn't
represent the value -1 IMO.
May 6 '06 #11
On Sat, 06 May 2006 14:13:40 +0200, "Alf P. Steinbach"
<al***@start.no > wrote:
* john:
Alf P. Steinbach wrote:

Integer promotion comes into play. That's primarily designed for
assignment, promoting to types with ever widening range of values that
can be represented. 'unsigned' can /represent/ all 'int' values (you
can convert from 'int' to 'unsigned' with well-defined unique result)
but not vice versa.


How is the int value -1 represented in unsigned int?


Modulo 2^n, where n is the number of bits in the value representation of
unsigned int.


Does the C++ standard require two's complement representation?
May 6 '06 #12
john wrote:

But why is the opposite, unsigned to int, undefined?
Shouldn't it just be the other way around?


It's a more or less arbitrary choice. For example, with 16-bit integers,
a signed int can hold values in the range -32767 to 32767; an unsigned
int can hold values in the range 0 to 65535. Going either way, there
will be values that can't be "correctly" represented. C chose to define
unsigned arithmetic more rigorously than signed, and C++ followed along.

--

Pete Becker
Roundhouse Consulting, Ltd.
May 6 '06 #13
* Olaf van der Spek:
On Sat, 06 May 2006 14:13:40 +0200, "Alf P. Steinbach"
<al***@start.no > wrote:
* john:
Alf P. Steinbach wrote:
Integer promotion comes into play. That's primarily designed for
assignment, promoting to types with ever widening range of values that
can be represented. 'unsigned' can /represent/ all 'int' values (you
can convert from 'int' to 'unsigned' with well-defined unique result)
but not vice versa.

How is the int value -1 represented in unsigned int?

Modulo 2^n, where n is the number of bits in the value representation of
unsigned int.


Does the C++ standard require two's complement representation?


No, but it requires the modulo 2^n "conversion " from signed to unsigned.

--
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?
May 6 '06 #14
> And I disagree, unsigned(-1) may have the same bit pattern but doesn't
represent the value -1 IMO.


unsigned int a = 4;
unsigned int b = 8;
unsigned int c = a - b; // any comment on this?
unsigned int d = c + 10; // how about this?

Looks to me that "negative" values are indeed not presented as such,
but atleast the arithmetic is guaranteed to work. Works for me. :)

May 6 '06 #15
FYI, the point is that how you ever going to know if unsigned int is
supposed to be 'negative' or not: you don't - the values are always,
absolutely, positively, positive.

In this case, ofcourse, you can take a look at a and b, but that is
besides the point already.

There comes a time, when you absolutely, positively, have to have
negate of a specific value. Want to know the lowest set bit in unsigned
integer?

pseudo: v & -v

If v is unsigned int, doing unary minus is kind of out of the question.
So you put your ninja outfit on and write instead: v & (0 - v) and the
compiler is none the wiser but compiles your crime against c++
programming. You leave the crime scene with the lowest set bit richer.

May 6 '06 #16
persenaama wrote:

There comes a time, when you absolutely, positively, have to have
negate of a specific value. Want to know the lowest set bit in unsigned
integer?

pseudo: v & -v

If v is unsigned int, doing unary minus is kind of out of the question.
No, it's well defined. The value is 2^n-v, where n is the number of bits
in an unsigned int.
So you put your ninja outfit on and write instead: v & (0 - v) and the
compiler is none the wiser but compiles your crime against c++
programming. You leave the crime scene with the lowest set bit richer.


All this graphic language obscures the fact that both of these
expressions have precisely defined meanings and they do exactly the same
thing, which is exactly what you want in this example. It may be that
your compiler is giving you warnings, but most compiler warnings these
days are about style and not about substance.

--

Pete Becker
Roundhouse Consulting, Ltd.
May 6 '06 #17
On 6 May 2006 10:07:38 -0700, "persenaama " <ju***@liimatta .org> wrote:
And I disagree, unsigned(-1) may have the same bit pattern but doesn't
represent the value -1 IMO.


unsigned int a = 4;
unsigned int b = 8;
unsigned int c = a - b; // any comment on this?
unsigned int d = c + 10; // how about this?

Looks to me that "negative" values are indeed not presented as such,
but atleast the arithmetic is guaranteed to work. Works for me. :)


I didn't say c and d are undefined in C++.
But I do say that c does not contain the value -4.
May 7 '06 #18
I got that, merely experienced a "so what!?" -moment and shared the
love. :)

May 7 '06 #19

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

Similar topics

0
2923
by: g | last post by:
Hi all. Maybe this question has been asked many times before, but I was not able to find any pointer. I apologize in advance, for it refers to a particular standard library implementation (GNU C++ version 3.x), but perhaps it's more general than that. The following program (to be compiled with g++ 3.x, 2.9x is not enough) #include <iostream> #include <string>
1
6166
by: Paul Edwards | last post by:
I have the following C program: #include <stdio.h> int main(void) { unsigned short x = 32768, y=16384; if (x > y) {
3
11038
by: Alex | last post by:
I have a problem about the comparison between signed and unsigned integer. See the following code: int foo() { int i; unsigned int j; if (i < j) {
2
5126
by: Frederick Gotham | last post by:
I just want to clarify my understanding of arithmetic and comparison between two different integer types. Phase (1): Integer Promotion ---------- All of the following types always get promoted to "signed int": signed char
4
16243
by: Gary Wessle | last post by:
Hi I am writing a code to open a space delimited data file, return the number of rows and columns, as well as return the nth column where n is user define number. I put all the cells in a loooong vector and loop in an incremental way to select the column of choice, here is the code which works but gives a warning ****************************************************************
8
3895
by: John Ratliff | last post by:
"comparison is always false due to limited range of data type" I get this warning with g++ when I compile some code and I'm not quite sure I understand it. I have a small file that I've read into a memory buffer. It is defined char sram; I need to check for a specific value within this buffer.
14
24285
by: Mosfet | last post by:
Hi, what is the most efficient way of doing a case insensitive comparison ? I am trying to write a universal String class and I am stuck with the case insensitive part : TCHAR is a char in MultiByte String env (MBCS) and wchar_t if UNICODE #if defined(WIN32) || defined(UNDER_CE)
6
11163
by: compcreator | last post by:
I have tried the following program. The problem is it is printing False I checked values for a and b but there is something wrong with the comparison. I thing it might be because of signed and unsigned conversion. Either b is upgraded to unsigned and the resulting value during comparison is 5 or a is downgraded to signed and the resulting value is lower than -1.
5
695
by: evanevankan2 | last post by:
I have a question about the warning 'comparison between signed and unsigned' I get from my code. It comes from the conditional in the outer for loop. I understand the warning, but I'm not sure what is the best way to prevent it. I can just change i to a type size_t or maybe put a cast in the conditional, but I don't know which way that is 'best'? Any ideas? I provided the code below for some context. And while we're at it, could you...
0
9719
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
10371
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
10374
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,...
1
7650
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
6877
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
5546
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...
0
5684
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4330
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
3853
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.