Assign a negative unsigned value to a signed one, right?

When I ran this:

int main() {
    unsigned a = 5;
    std::cout << -a << std::endl;
    int b = -a; 
    std::cout << b << std::endl;
    return 0;
}

I get this:

4294967291
-5

It seems to work, and I can accept a negative result unsignedand assign it int, but is it really always normal? Why?

When I try something that seems to me like a similar situation:

int c = 1;
int d = 3;
double x = c/d;
std::cout << x << std::endl;

I get 0(as expected).

PS: Maybe there is a fraud, and I did not find it, the closest I found this

+4
source share
2 answers

No . You have undefined features.

Here is a counterexample that UB creates when assigning a negated unsigned intto int:

unsigned u = (unsigned)std::numeric_limits<int>::max() - 1;
std::cout << "max int" << std::numeric_limits<int>::max() << '\n';
std::cout << "as unsigned - 1" << u << '\n';
std::cout << "negated:" << -u << '\n';
std::cout << std::boolalpha << ( std::numeric_limits<int>::max() < -u ) << '\n';
int s = -u;
std::cout << s << '\n';

: int 2'147'483'647, unsigned int 2'147'483'650; , int. , - undefined. , .

(2016-07-12: N4604) :

, . [: , , . - ]


{} -style, :

unsigned a = 5;
std::cout << -a << '\n';
int b{ -a }; // compiler detects narrowing conversions, warning/error
std::cout << b << '\n';
return 0;

, , -a , int, .

:

undefined ++?

C, ++:

, ?

:

http://en.cppreference.com/w/cpp/language/implicit_conversion

+4

, int 32 . .

0

Source: https://habr.com/ru/post/1653170/


All Articles