c++ - Overflowing signed/unsigned assignments and its results -


i'm reading stroustrup's book "the c++ programming language 4th edition" , have 3 questions regarding overflowing assignments (particularily signed/unsigned chars, book exemplifies). firstly, according standard 5/4 paragraph:

if during evaluation of expression, result not mathematically defined or not in range of representable values type, the behavior undefined.

(except when destination variable unsigned - result defined in such case). definition pertain assignments?

because in opinion there many contrary statements in book, in chapter 6. first 1 corresponds aforementioned paragraph, following comments doesn't:

variables of 3 char types can freely assigned each other. however, assigning large value signed char still undefined. example:

void g(char c, signed char sc, unsigned char uc) {     c = 255; //implementation-defined if plain chars signed , have 8 bits     c = sc; //ok     c = uc; //implementation-defined if plain chars signed , if uc's value large     sc = uc; //implementation-defined if uc's value large     uc = sc; //ok: conversion unsigned     sc = c; //implementation-defined if plain chars unsigned , if c's value large     uc = c; //ok: conversion unsigned } 

first question: since assigning large value ub, why comments it's implementation-defined?

next have following example:

to concrete, assume char 8 bits:

signed char sc = -160; unsigned char uc = sc; //uc == 116 (because 256-160==116) cout << uc; //print 't' 

second question: apart fact first assignment supposedly ub, formula has author used in order come 116? in test, uc got value of 96.

and last quote:

an integer can converted integer type. if destination signed, value unchanged if can represented in destination type; otherwise, value implementation-defined:

signed char sc = 1023; //implementation-defined

plausible results 127 , -1.

third question: again, apart fact contrary have been said earlier ub, why possible results 127 , -1? guess has one's , two's complement, precise formulas used?

1) implementation defined "a class of ub" - in other words, it's still ub, it's implementation responsible explaining how works, rather "you can't @ rely on operation". so, compiler still allowed explode computer if assign out-of-range char values. implementation can define "it chops 8-bit equivalent value".

2) 256 - 160 = 96 on calculator. bet on yours well. maybe author had different calculator? or it's 1 of things got changed last minute -150 -160, forgot change end result.

3) since it's "implementation defined", end being anything. since value 0x3ff in hex, can imagine either 0xff or 0x7f plausible values, depending on how implementation decides that. expect compilers use 0xff value.


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -