reinterpret_cast of signed int reference

Why is the result 4294967292 instead of -4 even when both integer types are signed?

#include <iostream>

void f(int & i)
{
    i = -4;
}

int main()
{
    long long i = 0;
    f(reinterpret_cast<int &>(i));
    std::cout << i << std::endl;
    return 0;
}

Upvotes: 1

Views: 587

Answers (1)

LogicStuff
LogicStuff

Reputation: 19607

long long seems to be 64-bit and int 32-bit number on your architecture. You're using 32-bit integer references, so you only modified the less significant half (you're evidently compiling on an ordinary x86 machine, which uses little endian and two's complement for signed integer representation).

The sign bit, as well as the more significant half are all 0s (as initialized). It would have to be 1s to print the same negative value:

0000 0000 0000 0000 0000 0000 0000 0000 1111 1111 1111 1111 1111 1111 1111 1100
^                                       ^
sign bit of long long                   sign bit of int

reinterpret_cast only guarantees that you get back your int with another reinterpret_cast, so you either print it as int, or use long long & parameter.

Upvotes: 6

Related Questions