M
Marc
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
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