473,670 Members | 2,397 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Unsigned & signed int

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
someone please explain the mechanics behind it . Is the unsigned int
converted to signed or is it vice-versa . Also , the same rules would
apply to char as well , right ?

Oct 2 '07 #1
6 6445
"Kislay" <ki***********@ gmail.comschrie b im Newsbeitrag
news:11******** **************@ 22g2000hsm.goog legroups.com...
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";
This is C++, not C, try comp.lang.c++. Or use printf() or puts().
Also the else branch is wrong "j is greater or equal" would be the correct
statement.
Since i is unsigned , j is greater . I know why , but vaguely . Can
someone please explain the mechanics behind it . Is the unsigned int
converted to signed or is it vice-versa . Also , the same rules would
apply to char as well , right ?
in C, I think the signed int would get promoted to unsigned int. And yes,
chars should do the same. That's why you get 'j is greater' (in C, not sure
about C++)

if((int)i>j)
would give the correct/expected output.

Strange, I'd have expected my compiler to give a warning about the implicit
conversion ...
Bye, Jojo
Oct 2 '07 #2
On Oct 2, 7:34 pm, Kislay <kislaychan...@ gmail.comwrote:
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
someone please explain the mechanics behind it . Is the unsigned int
converted to signed or is it vice-versa . Also , the same rules would
apply to char as well , right ?

Rule 1: Things get promoted to SIGNED integer types where possible,
otherwise UNSIGNED.

Rule 2: The smaller of the two types involved in the operation has to
change to the bigger type.

Rule 3: If you're left with two types of the same size, but where one
is signed and the other unsigned, they both become unsigned.

Firstly, let's start with the types smaller than int. These types are
as follows:

signed char
unsigned char
signed short
unsigned short

The C Standard guarantees the following:
CHAR_MAX <= SHRT_MAX <= INT_MAX <= LONG_MAX
and also the following:
UCHAR_MAX <= USHRT_MAX <= UINT_MAX <= ULONG_MAX

Before you can do ANYTHING to any of the integer types smaller than
int, they must be promoted. As mentioned before, they promote to
SIGNED where possible, otherwise unsigned. Signed char and signed
short will always promote to signed int on every implementation. As
for unsigned char and unsigned short, they will promote to signed int
on some system, but unsigned int on other systems, depending on
whether all the values of the smaller type can be stored in signed
int. After the promotion of the smaller type takes place, you could
still be left with the following combinations:

1: (unsigned int) + (signed int)
2: (int) + (long)
3: (unsigned int) + (long)
4: (unsigned int) + (unsigned long)

In number 1, both types are the same size but one of them is unsigned,
so they both become unsigned.
In number 2, the int has to become a long.
In number 3, the int has to become a long, but we don't know if all
the values of unsigned int can be stored in a signed long. Therefore,
on some systems this will become an unsigned long, while on others it
will become a signed long. Once the two types are either kind of long,
they will become unsigned long if either of them is unsigned,
otherwise they'll stay as signed long.
In number 4, they'll both become unsigned long.

I suppose the thought process is as follows:

1: Promote things that are smaller than int.
2: Match the sizes (but being careful about whether the small type
will become signed or unsigned of the bigger type).
3: Once the sizes are match, match the signs (if one of them is
unsigned, then they both become unsigned).

Now... as for the rules for converting from unsigned to signed... what
you do is take the max value of the unsigned type, add 1 to it, and
then add it to the signed value.

So let's take -1. Let's pretend that UCHAR_MAX is 255. Therefore we
add as follows:

-1 + (255 + 1) = 255

Therefore the following two are equivalent:

char unsigned c = UCHAR_MAX;
char unsigned c = -1;

As are the following:

short unsigned su = USHRT_MAX - 5;
short unsigned su = -6;

I'll edit your own original code to show you exactly what's going to
happen:

unsigned int i=10;

int j= - 2; // minus 2

unsigned j_changed_to_un signed = UINT_MAX - 1;

if(i j_changed_to_un signed)
cout<<"i is greater";
else
cout<<"j_change d_to_unsigned is greater";
You might wanna use printf instead of cout on this newsgroup though ;)

Martin
Oct 2 '07 #3
Now... as for the rules for converting from unsigned to signed...

signed to unsigned

Oct 2 '07 #4
Kislay wrote:
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";
Note that however cout is defined, and to use the "<<" operator on it is
really ought to be an unsigned integral type, it makes no sense to shift
it left by a string constant. And you probably want to lose the space
between '-' and '2', as well as the silly comment.
Since i is unsigned , j is greater . I know why , but vaguely . Can
someone please explain the mechanics behind it . Is the unsigned int
converted to signed or is it vice-versa . Also , the same rules would
apply to char as well , right ?
I believe the question you meant to ask is explicitly covered in the
FAQ. See Question 3.19 "Q: What's the difference between the ``unsigned
preserving'' and ``value preserving'' rules?" where, among other things,
this code
unsigned short us = 10;
int i = -5;
if(i us)
printf("whoops! \n");
is discussed.
The question and answer can be found at
<http://c-faq.com/expr/preservingrules .html>, but you really want to
start trying to digest the FAQ as a whole <http://c-faq.com/index.html>.
Oct 2 '07 #5
Martin Wells wrote:
The C Standard guarantees the following:
CHAR_MAX <= SHRT_MAX <= INT_MAX <= LONG_MAX
You misspelled "SCHAR_MAX" .

--
pete
Oct 2 '07 #6
On Oct 3, 10:46 am, Martin Wells <war...@eircom. netwrote:
>
char unsigned c = UCHAR_MAX;
char unsigned c = -1;
JKop, JKop, is that you?

Oct 3 '07 #7

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

Similar topics

19
6468
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?)
34
16665
by: Andy | last post by:
Hi, Are 1 through 4 defined behaviors in C? unsigned short i; unsigned long li; /* 32-bit wide */ 1. i = 65535 + 3; 2. i = 1 - 3; 3. li = (unsigned long)0xFFFFFFFF + 3; 4. li = 1 - 3;
10
15647
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 */
16
5118
by: TTroy | last post by:
Hello, I'm relatively new to C and have gone through more than 4 books on it. None mentioned anything about integral promotion, arithmetic conversion, value preserving and unsigned preserving. And K&R2 mentions "signed extension" everywhere. Reading some old clc posts, I've beginning to realize that these books are over-generalizing the topic. I am just wondering what the difference between the following pairs of terms are: 1)...
4
15344
by: techie | last post by:
I have defined a number of unsigned integer types as follows: typedef unsigned char uint8; typedef unsigned short uint16; typedef unsigned int uint32; typedfe long long uint64; Is it necessary to explicitly cast from one type of unsigned integer type to another even though they do so implicitly?
10
3295
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
4
5577
by: RainX | last post by:
Hi all, I'm new to the site and i was hoping someone here could help me out I was giving the following code and asked to determine whether the results giving any values for n1 and n2 (including int_max and int_min) would be either true (1) or False (0). I know it has to do with limits, unsigned int's & 2's compliments, but i don't know how to go about answering. Would love it if someone would help me try to understand this.. Take care ...
7
5043
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
9
2309
by: Ido Yehieli | last post by:
Hi, from what i've read (http://tigcc.ticalc.org/doc/ keywords.html#short) and unsigned int should normally be in the range 0 to 65535. However, compiling and running this program: #include <stdio.h> int main(){ unsigned int y=1; y-=2;
0
8469
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
8903
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...
1
8592
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
8661
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
7419
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...
0
5684
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
4211
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...
2
2042
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1794
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.