Summation on HP 42S
|
09-30-2018, 05:28 PM
(This post was last modified: 09-30-2018 05:34 PM by ijabbott.)
Post: #52
|
|||
|
|||
RE: Summation on HP 42S
(09-30-2018 03:03 PM)Albert Chan Wrote:(09-29-2018 09:10 PM)ijabbott Wrote: Curiously, replacing `i += i;` with `i <<= 1` in the code ... it just returns the value 31. I've no idea why the i <<= 1; version works. By the rules of C, it would be at liberty to turn it into an infinite loop as it did for i += i; (although that is not a terribly useful thing to do!). The i += (unsigned)i case works because there is no undefined behaviour. The result of the addition will be of type unsigned int and that needs to be converted back to a signed int. If the value does not fit (i.e. it's greater than INT_MAX) then the conversion is implementation-defined or an implementation-defined signal is raised. In the case of GCC, it will be defined as mapping onto a negative value by 2's complement. The key point is that it isn't undefined behaviour and that GCC will define (unsigned int)0x80000000 as being converted to (int)-0x80000000, and so the loop will terminate after 31 iterations (in the abstract machine). (In practice, the optimiser can get rid of the loop by working out the result at compile time.) [EDIT - removed unfinished bits of reply I didn't mean to post!] [EDIT - it's almost as if I'm having a "Senior" moment! (Post count: 299)] — Ian Abbott |
|||
« Next Oldest | Next Newest »
|
User(s) browsing this thread: 1 Guest(s)