On a ones-complement platform, what would the following code print?
#include <iostream>
int main() {
int i = 1, j = -1;
std::cout << i+j << std::endl;
return 0;
}
I would suspect it would print "0" instead of "-0", but I can't seem to find anything authoritative.
Edit: To clarify, I am interested in how -0 would be printed, several people have suggested that in practice, the implementation of ones-compliment might not generate a negative zero with the above code.
In those cases, the following has been suggested to actually generate a -0:
#include <iostream>
int main() {
std::cout << ~0 << std::endl;
return 0;
}
The question still remains: what will this print?
First of all, just to clarify thing, crafting a negative zero using bitwise operations and then using the resulting value is not portable. That said, nothing specifies in the documentation of fprintf
(thus, of std::basic_ostream::operator<<(int)
) whether the sign bit in the representation of int corresponds to a padding bit in the representation of unsigned
or an actual value bit.
As a conclusion, this is unspecified behaviour.
#include <iostream>
int main() {
std::cout << ~0 << std::endl;
return 0;
}
Indeed adding n
to -n
should give you a negative zero. But the generation of -0 doesn't happen in practice since 1's complement addition uses a technique called a complementing subtractor (the second argument is complemented and subtracted from the first).
(The idiomatic way of getting a signed floating point zero doesn't apply here since you can't divide an integer by zero).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With