jeudi 1 décembre 2016

Why is this expression being unsigneded?

On x86_64 CentOS 7 GCC 4.8.5 C++11:

#include <iostream>

int main()
{
    std::cout << ((ssize_t)1 - (size_t)5) << '\n';
}

// Output: 18446744073709551612

But:

#include <iostream>

int main()
{
    std::cout << ((ssize_t)1 - (unsigned int)5) << '\n';
}

// Output: -4

And on i686 CentOS 6 GCC 4.8.2 C++11, they both give 4294967292 so I have to do this:

#include <iostream>

int main()
{
    std::cout << ((ssize_t)1 - (ssize_t)5) << '\n';
}

// Output: -4

An extremely contrived example, obviously, and I understand that I'm hitting various clauses in the integral promotion rules depending on the platform/implementation-defined type equivalences, but on a Thursday my brain can't unravel them for a rigourous assessment.

What exactly is the sequence of standard rules that leads me to these results?

Aucun commentaire:

Enregistrer un commentaire