R
Rob Williscroft
Ioannis Vranos wrote in in
comp.lang.c++:
No on a 1's complement machine (say 16 bit for example -1 will
be represented in binary as 10000000 00000001 high bit (sign bit)
and byte first. unsigned( -1 ) is 11111111 11111111 which is
std::numeric_limits< unsigned >::max().
You must read the union member that was last assigned.
3.9.1/3 says that INT_MAX 01111111 1111111 has the same value
representation in signed and unsigned.
Doing:
nice.i = INT_MAX;
cout << nice.u;
is still UB, but in practice its only UB because the standard
says so. In theory (for example) a compiler could diagnose the
UB and refuse to compile, its UB, its free to *anything* it wants
and still be a conforming compiler.
Rob.
comp.lang.c++:
Rob Williscroft wrote:
Then JKOP is right!
#include <iostream>
union whatever
{
unsigned u;
signed i;
};
int main()
{
using namespace std;
whatever nice;
nice.i=-1;
cout<<nice.u<<" "<<static_cast<unsigned>(-1)<<endl;
}
Based on the standard nice.u above will always be equal to
numeric_limits<unsigned>::max()!
No on a 1's complement machine (say 16 bit for example -1 will
be represented in binary as 10000000 00000001 high bit (sign bit)
and byte first. unsigned( -1 ) is 11111111 11111111 which is
std::numeric_limits< unsigned >::max().
You must read the union member that was last assigned.
3.9.1/3 says that INT_MAX 01111111 1111111 has the same value
representation in signed and unsigned.
Doing:
nice.i = INT_MAX;
cout << nice.u;
is still UB, but in practice its only UB because the standard
says so. In theory (for example) a compiler could diagnose the
UB and refuse to compile, its UB, its free to *anything* it wants
and still be a conforming compiler.
Rob.