简体   繁体   中英

Assigning an out-of-range integer to a signed char type

signed char a = 128;
Assuming that a byte is 8 bits, is this undefined?
What I know is that assigning an out-of-range value to a signed type is undefined, but Bjarne Stroustrup says in C++ Programming language that if I assign the integer 255 to a char on an 8-bits bytes machine where a char is signed the result is -1.

signed char a = 128;
Assuming that a byte is 8 bits, is this undefined?
What I know is that assigning an out-of-range value to a signed type is undefined, but Bjarne Stroustrup says in C++ Programming language that if I assign the integer 255 to a char on an 8-bits bytes machine where a char is signed the result is -1.

By default in C and C++, result of the overflow/underflow operation is UNDEFINED . What happens if you overflow/underflow a signed variable type is obsecure which means it could be wrapped around(it is assumed by many compilers) or may dump the core or terminates the program etc.
But compiler developers usually doesn't strictly conform to this definition and usually wraps around these built-in types

Here's a section from The C++ Programming Language 4th By Edition Bjarne Stroustrup(page.259)

void f()
{
    int i = 1;
    while (0 < i) ++i;
    cout << "i has become negative!" << i << '\n';
}
//This will (eventually) try to increase i past the largest integer. What happens then is undefined, but
//typically the value ‘‘wraps around’’ to a negative number (on my machine −2147483648).

here what gnu says about it

Also, overflow can occur when converting an out-of-range value to a signed integer type. Here a standard implementation must define what happens, but this might include raising an exception. In practice all known implementations support silent wraparound in this case, so you need not worry about other possibilities. Blockquote

And please check this great article and see how the other fundamental programs rely on ungranteed signed overflow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM