Reputation: 4454
I have a simple question that is motivated by safe coding.
I encountered a situation where I have to assign the negative value of the remainder of division or 0
to an int
variable, so I used the following notation:
int a = -(b % c);
where both b
and c
are positive integers. The expression (b % c)
will yield a positive number or 0
and a
will be assigned the negative value of the result.
In the event that (b % c)
yields 0
, what does -0
evaluate to? 0
or negative 0
? and what are the implications if the latter happened?
P.S I don't know what negative 0
is.
Upvotes: 3
Views: 124
Reputation: 223161
-(b % c)
cannot generate a negative 0 because C 2018 6.2.6.2 3 says:
If the implementation supports negative zeros, they shall be generated only by:
— the
&
,|
,^
,~
,<<
, and>>
operators with operands that produce such a value;— the
+
,-
,*
,/
, and%
operators where one operand is a negative zero and the result is zero;— compound assignment operators based on the above cases.
Even if we interpret the above to include -
as a unary operator, we have been given that b
and c
are positive integers, so b % c
cannot produce a negative zero, so the operand to -
in -(b % c)
is not a negative zero.
If ==
is used to compare a negative zero and a non-negative zero, it produces true, as ==
operates based on the values of the operands, not their representations.
Negative zeros are extremely rare for integers in modern C implementations. Modern implementations overwhelmingly use two’s complement, which does not have a negative zero. Only specialized/historic/archaic implementations might use the alternative integer representations that have negative zeros (one’s complement and sign-and-magnitude). Floating-point representations commonly have negative zeros, but they are equal to positive zeros in comparisons for equality by value (the ==
, !=
, <
, >
, <=
, and >=
operators).
Upvotes: 6