Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does std::cout print negative zero in a ones-complement system?

Tags:

c++

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?

like image 504
Tyzoid Avatar asked Oct 15 '15 14:10

Tyzoid


Video Answer


2 Answers

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;
}
like image 180
YSC Avatar answered Oct 14 '22 08:10

YSC


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).

like image 25
Bathsheba Avatar answered Oct 14 '22 08:10

Bathsheba