473,732 Members | 2,190 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A question about taking the absolute value of an integer

I really don't understand how something like..

#define abs(x) (((x) < 0) ? -(x) : (x))

could cause a possible overflow.

Jan 5 '08 #1
7 2891
In article <f9************ *************** *******@1g2000h sl.googlegroups .com>,
Chad <cd*****@gmail. comwrote:
>I really don't understand how something like..
>#define abs(x) (((x) < 0) ? -(x) : (x))
>could cause a possible overflow.
e.g., INT_MIN might be -32768.
-(-32768) ---32768 but INT_MAX might be 32767

This is an issue in any implementation that uses twos complement
(unless it reserves the minimum integral value for some reason,
which would be quite unusual.)

It might help to look at the binary values involved.
On a system with a two-byte unsigned short, for example,
SHORT_MIN would be 0x8000 . To take the negative,
toggle each bit and then add 1 to the result. Toggling each
bit of 0x8000 would be 0x7FFF; add 1 and you get 0x8000 which
is the original value back again.
--
"I was very young in those days, but I was also rather dim."
-- Christopher Priest
Jan 5 '08 #2
Chad wrote:
I really don't understand how something like..

#define abs(x) (((x) < 0) ? -(x) : (x))

could cause a possible overflow.
Find a machine where INT_MIN + INT_MAX == -1 (that's
nearly every machine nowadays) and evaluate abs(INT_MIN).

--
Eric Sosman
es*****@ieee-dot-org.invalid
Jan 5 '08 #3
On Jan 5, 1:10 pm, Eric Sosman <esos...@ieee-dot-org.invalidwrot e:
Chad wrote:
I really don't understand how something like..
#define abs(x) (((x) < 0) ? -(x) : (x))
could cause a possible overflow.

Find a machine where INT_MIN + INT_MAX == -1 (that's
nearly every machine nowadays) and evaluate abs(INT_MIN).

--
Eric Sosman
esos...@ieee-dot-org.invalid

% more abs.c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int main(void)
{
printf("%u\n",a bs(INT_MIN));
return 0;
}

% ./abs
2147483648
Jan 5 '08 #4
Op Sat, 5 Jan 2008 13:24:09 -0800 (PST) schreef Chad:
On Jan 5, 1:10 pm, Eric Sosman <esos...@ieee-dot-org.invalidwrot e:
>Chad wrote:
>>I really don't understand how something like..
>>#define abs(x) (((x) < 0) ? -(x) : (x))
>>could cause a possible overflow.

Find a machine where INT_MIN + INT_MAX == -1 (that's
nearly every machine nowadays) and evaluate abs(INT_MIN).

--
Eric Sosman
esos...@ieee-dot-org.invalid


% more abs.c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int main(void)
{
printf("%u\n",a bs(INT_MIN));
return 0;
}

% ./abs
2147483648
Try printf("%n\n" ....
the result will be a negative number. And an absolute value shall be
positive ;-(
--
Coos
Jan 5 '08 #5
In article <a4************ *************** *******@t1g2000 pra.googlegroup s.com>,
Chad <cd*****@gmail. comwrote:
>% more abs.c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int main(void)
{
printf("%u\n",a bs(INT_MIN));
return 0;
}

% ./abs
2147483648
Perhaps you will see your mistake if you change the printf line
to:

printf("%u %u\n",INT_MIN, abs(INT_MIN));

-- Richard
--
:wq
Jan 5 '08 #6
On Sat, 5 Jan 2008 22:33:40 +0100, Coos Haak <ch*****@hccnet .nl>
wrote:
Op Sat, 5 Jan 2008 13:24:09 -0800 (PST) schreef Chad:
printf("%u\n",a bs(INT_MIN));
<snip: appears to work>
Try printf("%n\n" ....
the result will be a negative number. And an absolute value shall be
positive ;-(
%d or %i. %n is something quite different, and wrong here.

- formerly david.thompson1 || achar(64) || worldnet.att.ne t
Jan 22 '08 #7
Op Tue, 22 Jan 2008 05:22:40 GMT schreef David Thompson:
On Sat, 5 Jan 2008 22:33:40 +0100, Coos Haak <ch*****@hccnet .nl>
wrote:
>Op Sat, 5 Jan 2008 13:24:09 -0800 (PST) schreef Chad:
>> printf("%u\n",a bs(INT_MIN));
<snip: appears to work>
>Try printf("%n\n" ....
the result will be a negative number. And an absolute value shall be
positive ;-(

%d or %i. %n is something quite different, and wrong here.
Absolutely, thanks.
--
Coos
Jan 22 '08 #8

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

Similar topics

4
3372
by: ac | last post by:
Hi, I have to customize a component (in this case Windows Media Player) so that a circular window is shown upon the player. That is, suppose you have a movie playing (in the ordinary rectangle window), I'd like to create some sort of mask which only allows to watch inside the circle (as if someone is viewing through a peephole or spyhole..) Is there any possible way to do this? This is targetted to WMP, but maybe it can be done with...
34
16867
by: Christopher Benson-Manica | last post by:
I'm trying to compute the absolute value of an integer using only bitwise operators... int x; sscanf( "%d", &x ); printf( "%d\n", (x^((~((x>>31)&1))+1)) + ((x>>31)&1) ); That works, but it assumes 32 bit integers. Is there a portable/standard way to do this? Or are ANSI integers always 32 bits? If not, is using sizeof(int) * 8 - 1 as the shift value an acceptable alternative?
66
4130
by: Cor | last post by:
Hi, I start a new thread about a discussion from yesterday (or for some of us this morning). It was a not so nice discussion about dynamically removing controls from a panel or what ever. It started by an example from me, that was far from complete and with typing errors, but basically it had the meaning to show that removing controls reversible was the nicest method. This was a lets say conclusion (but what is that in a newsgroup) in a...
35
2577
by: Cor | last post by:
Hallo, I have promised Jay B yesterday to do some tests. The subject was a string evaluation that Jon had send in. Jay B was in doubt what was better because there was a discussion in the C# newsgroup on 25 September. The regular expressions where in that newsgroup too involved. I told yesterday night, to Jay that I would test all 4 methods and the stupid method I was thinking of the first time that night when I saw Jon's
4
63496
by: Bill Nguyen | last post by:
How do I get the absolute value of an expression in VB.NET? The new ABS function looks scary to me! Thanks Bill
7
2194
by: Yuri_Юрий | last post by:
I'm confused about the VARIABLE LENGTH ARRAYS. {scanf("%d",&n);float a;} In which compiler can I use it? I tried VC++6.0 SP6,but it's reported error:CONSTANT EXPRESSION! Another question, What the differences between: (1)ElemType array (2)array=(ElemType*)malloc(N*size of(ElemType)) or array=(ElemType*)calloc(N,size of(ElemType))
60
4779
by: deko | last post by:
As I understand it, most browser manufacturers have agreed on 16px for their default font size. So, this should be an accurate conversion for percentages: px % 16 = 100 14 = 87.5 13 = 81.25
10
8393
by: JDT | last post by:
Hi, Can someone provide me an example that uses std::max_element() (probablly the predicate version) to return the max "absolute" integer in a vector? Your help is much appreciated. Tony ps.
4
2811
by: Bails | last post by:
Hi Im an absolute beginner in programming and am using VB.Net Express. To start my larning I decided to do a "Real World" app instead of "hello world" and am creating a Poker Countdown clock. I pretty much have most things under control and have set it up as follows: Form 1 Contains a DataGridView where users enter in information includeing the length of each round, small blind & big blind (its for
0
9445
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
9306
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
9234
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
9180
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
6030
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
4548
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
4805
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3259
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
3
2177
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.