473,603 Members | 2,601 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Semantics of unary minus

Hi,

I've been lurking on clc for a few months now, and want to start by
thanking the regulars here for opening my eyes to a whole new dimension
of "knowing c". Considering I had never even touched the standards a
year ago, though I graduated in embedded SW development...

Anyway, to the problem at hand: I've stumbled upon the following
construct at work recently, and cannot really make up my mind about the
standard's take on the matter.

int a;
unsigned int b;

if(a < 0) {
b = -a;
}

I just can't decide if this is valid when a's value is -32768 (admitting
16 bit ints). I can't see how the standard's wording on unary minus
semantics allows for 2's complement asymmetry. C99 says:

"The result of the unary - operator is the negative of its (promoted)
operand. The integer promotions are performed on the operand, and the
result has the promoted type." (I'm also slightly suspicious about the
disappearance of "value" as compared to the semantics of unary plus...)

Unless I'm mistaken, a won't be promoted (being an int), so there might
be no such thing as "the negative of its (promoted) operand"? I feel
like the standard tells me I might end up with an int worth 32768...
(still assuming 16 bit ints)? Or should I consider there is an implied
"if-it-fits-otherwise-overflow"?

I couldn't find any help through google or in the FAQ, so I'd really
appreciate any clarification.

Marc
Feb 12 '06 #1
13 5082
"Marc" <no****@mail.co m> wrote in message
news:ds******** *****@news.t-online.com...
int a;
unsigned int b;

if(a < 0) {
b = -a;
}

I just can't decide if this is valid when a's value is -32768 (admitting
16 bit ints). I can't see how the standard's wording on unary minus
semantics allows for 2's complement asymmetry. C99 says:


-a overflows and typically yields -32768 without a trap
(though an implementation doesn't have to). The conversion
is 2^16 - 32768, which is 32768. So you luck out.

Converting to unsigned long doesn't work quite as well.
It is much safer to write "b = 0U - a" instead.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Feb 12 '06 #2
Marc wrote:
Hi,

I've been lurking on clc for a few months now, and want to start by
thanking the regulars here for opening my eyes to a whole new dimension
of "knowing c". Considering I had never even touched the standards a
year ago, though I graduated in embedded SW development...

Anyway, to the problem at hand: I've stumbled upon the following
construct at work recently, and cannot really make up my mind about the
standard's take on the matter.

int a;
unsigned int b;

if(a < 0) {
b = -a;
}

I just can't decide if this is valid when a's value is -32768 (admitting
16 bit ints). I can't see how the standard's wording on unary minus
semantics allows for 2's complement asymmetry. C99 says:

"The result of the unary - operator is the negative of its (promoted)
operand. The integer promotions are performed on the operand, and the
result has the promoted type." (I'm also slightly suspicious about the
disappearance of "value" as compared to the semantics of unary plus...)

Unless I'm mistaken, a won't be promoted (being an int), so there might
be no such thing as "the negative of its (promoted) operand"? I feel
like the standard tells me I might end up with an int worth 32768...
(still assuming 16 bit ints)? Or should I consider there is an implied
"if-it-fits-otherwise-overflow"?

I couldn't find any help through google or in the FAQ, so I'd really
appreciate any clarification.


Yes, two's complement is asymmetric about zero: there
is a negative number whose absolute value is not representable.
(The Standard actually permits an implementation to dodge this
asymmetry by defining "all ones" to be a trap representation;
I've never heard of an implementation that does so.)

However, that doesn't mean unary minus is undefined: it's
only undefined if its operand has an inappropriate value. This
is really no different from the situation with binary minus:

"The result of the binary - operator is the difference
resulting from the subtraction of the second operand
from the first." (6.5.6/6)

This is not to be taken as implying that all subtractions must
produce mathematically correct results: `INT_MIN - 42', for
example, is clearly not going to produce a value less than
INT_MIN.

When this sort of thing happens, another provision of the
Standard takes over:

"If an _exceptional condition_ occurs during the
evaluation of an expression (that is, if the result
is not mathematically defined or not in the range of
representable values for its type), the behavior is
undefined." (6.5/5)

So: If you try to negate (or take the absolute value of)
INT_MIN on a system where `INT_MIN + INT_MAX' is not zero, the
C language does not specify the outcome -- anything can happen,
at least in principle. The commonest behavior is that the
overflow is ignored, and the resulting representation (all ones)
is equal to INT_MIN again: INT_MIN is its own negation on most
two's-complement systems. However, this should be thought of
as a quirk of those systems, not as part of the C language.

--
Eric Sosman
es*****@acm-dot-org.invalid
Feb 12 '06 #3
Marc wrote:
int a; -a; "if-it-fits-otherwise-overflow"?


Yes.
"overflow" as in "undefined behavior".

It's a point of trivia which also comes up when writing itoa,
that there is no integer type which is guaranteed
to be able to represent the magnitude of INT_MIN.

--
pete
Feb 12 '06 #4

"Marc" <no****@mail.co m> wrote in message
news:ds******** *****@news.t-online.com...
Hi,

I've been lurking on clc for a few months now, and want to start by
thanking the regulars here for opening my eyes to a whole new dimension
of "knowing c". Considering I had never even touched the standards a
year ago, though I graduated in embedded SW development...

Anyway, to the problem at hand: I've stumbled upon the following
construct at work recently, and cannot really make up my mind about the
standard's take on the matter.

int a;
unsigned int b;

if(a < 0) {
b = -a;
}

I just can't decide if this is valid when a's value is -32768 (admitting
16 bit ints). I can't see how the standard's wording on unary minus
semantics allows for 2's complement asymmetry. C99 says:

"The result of the unary - operator is the negative of its (promoted)
operand. The integer promotions are performed on the operand, and the
result has the promoted type." (I'm also slightly suspicious about the
disappearance of "value" as compared to the semantics of unary plus...)

Unless I'm mistaken, a won't be promoted (being an int), so there might
be no such thing as "the negative of its (promoted) operand"? I feel
like the standard tells me I might end up with an int worth 32768...
(still assuming 16 bit ints)? Or should I consider there is an implied
"if-it-fits-otherwise-overflow"?

I couldn't find any help through google or in the FAQ, so I'd really
appreciate any clarification.


I'm not going to help you comprehend the spec. There are a few other people
here better at that than me. But, I can tell how the 16-bit and 32-bit
compilers that I use work in this area. The 16-bit compilers will not
convert -32768. It remains negative. But, they will convert -32767 (to -1)
to +32767 (to +1). The 32-bit compilers convert -32768 to +32768.
Basically, if it won't fit into the converted type, it doesn't get
converted.
Rod Pemberton

Feb 12 '06 #5
pete wrote:

Marc wrote:
int a;

-a;

"if-it-fits-otherwise-overflow"?


Yes.
"overflow" as in "undefined behavior".

It's a point of trivia which also comes up when writing itoa,
that there is no integer type which is guaranteed
to be able to represent the magnitude of INT_MIN.


You can see what INT_MIN expands to on your implementation.
It might be something like (-32767 - 1),
if you have two's complement representation of negative integers.

/* BEGIN new.c */

#include <stdio.h>
#include <limits.h>

#define str(s) # s
#define xstr(s) str(s)

int main(void)
{
puts("INT_MIN is " xstr(INT_MIN));
return 0;
}

/* END new.c */

--
pete
Feb 12 '06 #6
Eric Sosman wrote:
[...]
When this sort of thing happens, another provision of the
Standard takes over:

"If an _exceptional condition_ occurs during the
evaluation of an expression (that is, if the result
is not mathematically defined or not in the range of
representable values for its type), the behavior is
undefined." (6.5/5)

So: If you try to negate (or take the absolute value of)
INT_MIN on a system where `INT_MIN + INT_MAX' is not zero, the
C language does not specify the outcome -- anything can happen,
at least in principle. The commonest behavior is that the
overflow is ignored, and the resulting representation (all ones)
is equal to INT_MIN again: INT_MIN is its own negation on most
two's-complement systems. However, this should be thought of
as a quirk of those systems, not as part of the C language.


Ah yes ... 6.5/5 states exactly what I was looking for. Thanks a lot for
the pointer - guess I still have a cover-to-cover reading to do ...

As you and others suggested, the negation did work on our system, now I
know for sure it was just "lucking-out" from a standard's point of view.

Thanks all for the answers,

Marc
Feb 12 '06 #7
Eric Sosman wrote:

<snip: question about unary minus overflowing for INT_MIN>
Yes, two's complement is asymmetric about zero: there
is a negative number whose absolute value is not representable.
(The Standard actually permits an implementation to dodge this
asymmetry by defining "all ones" to be a trap representation;
I've never heard of an implementation that does so.)


ITYM a 1 followed by all 0s. All ones is -1 in two's complement.

Feb 13 '06 #8
Antonio Contreras wrote:

Eric Sosman wrote:

<snip: question about unary minus overflowing for INT_MIN>
Yes, two's complement is asymmetric about zero: there
is a negative number whose absolute value is not representable.
(The Standard actually permits an implementation to dodge this
asymmetry by defining "all ones" to be a trap representation;
I've never heard of an implementation that does so.)


ITYM a 1 followed by all 0s. All ones is -1 in two's complement.


He's talking about negative zero.
A one followed by all zeros, is negative zero
in sign and magnitude representation.
All ones is negative zero in one's complement representation.
There's different ways for an implementation
to deal with negative zero, trapping is one of them.

--
pete
Feb 13 '06 #9
pete wrote:
Antonio Contreras wrote:

Eric Sosman wrote:

<snip: question about unary minus overflowing for INT_MIN>
Yes, two's complement is asymmetric about zero: there
is a negative number whose absolute value is not representable.
(The Standard actually permits an implementation to dodge this
asymmetry by defining "all ones" to be a trap representation;
I've never heard of an implementation that does so.)


ITYM a 1 followed by all 0s. All ones is -1 in two's complement.


He's talking about negative zero.
A one followed by all zeros, is negative zero
in sign and magnitude representation.
All ones is negative zero in one's complement representation.
There's different ways for an implementation
to deal with negative zero, trapping is one of them.


But he was talking about two's complement. And AFAIK the standard
allows a two's complement representation with trap representations . In
this case the obvious pattern for a trap representation is a 1 followed
by all 0s, which implies that INT_MIN = - INT_MAX

Feb 13 '06 #10

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

Similar topics

3
3893
by: Carlos Ribeiro | last post by:
I was checking the Prolog recipe in the Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303057 It's a clever implementation that explores some aspects of Python that I wasn't aware of. One of them is the unary plus operator, that calls the __pos__ method. It's something that can be highly useful in my own experiments with the use of classes as a tool for generic declarative descriptions of objects -- UI forms,...
2
1879
by: Dave Theese | last post by:
Am I correct in saying that it is not possible to overload unary + and unary -?
6
8780
by: Andrew Ward | last post by:
Hi All, I tried to compile the following line: pair<long, ulong> cr3(make_pair(-2147483648L, 2147483647)); but get this error: unary minus applied to unsigned type, result still unsigned. But in my c++ book is says that the postfix L forces the integer to be signed.
5
2625
by: Ruben Campos | last post by:
Some questions about this code: template <typename T> class MyTemplate; template <typename T> MyTemplate <T> operator- (const MyTemplate <T> & object); template <typename T> MyTemplate <T> operator- (const MyTemplate <T> & object1, const MyTemplate <T> & object2); template <typename T> class MyTemplate
21
1884
by: Paul Steckler | last post by:
Here's some code that's giving me differing results, depending on the compiler. typedef foo { int A,B; } FOO; int main() {
2
2367
by: Javier Estrada | last post by:
1. For types smaller than int, when I compile: class MyClass { static void Main(string args) { x = 10; y = -x; }
6
2581
by: Matthew Cook | last post by:
I would like to overload the unary minus operator so that I can negate an instance of a class and pass that instance to a function without creating an explicit temporary variable. Here is an example: #include <iostream> using namespace std; class Object { public:
28
5063
by: dspfun | last post by:
I'm trying to get a good understanding of how unary operators work and have some questions about the following test snippets. int *p; ~!&*++p--; It doesn't compile, why? The problem seems to be the ++, the compiler says: "Error: invalid l-value in increment". int i = 10; ~!*&i++;
16
4689
by: JoseMariaSola | last post by:
How may operators and operands does (typename) expression has? I'd say one operator, the cast operator, and two operands: typename and expression. But everywhere I read, cast is categorized as an unary operator. Why is that? Is it just a syntax cotegory? Thanks.
0
8405
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
8060
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
6735
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
5878
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
5441
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
3903
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
3951
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2430
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
1
1514
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.