Why assign out-of-range value to signed integral type will generate machine depedent results?

Can anyone give me an example of a value about how can it varies dependent on the machine?

I just cannot think of any. Thanks.
http://ideone.com/V9rgSC
http://ideone.com/LbogiH
As you can see in the first example after assigning 267 to unsigned char we got 255
In second one — 11
Note, that it was on the same machine and programs were compiled with the same compiler and same parameters. That is why you should never allow undefined behavior in your program. BTW, if compiler will generate code for one of those programs which will steal your credit card number, it will be completely standard compliant: compiler have rights to do that.

Edit, ow, you probaly wanted not assigning out-of-range but signed overflow.
Sadly I do not have access to machines which does not uses 2s complement right now.
In that cas read these links:
http://stackoverflow.com/questions/3948479/integer-overflow-and-undefined-behavior
http://stackoverflow.com/questions/16188263/is-signed-integer-overflow-still-undefined-behavior-in-c
http://stackoverflow.com/questions/18195715/why-is-unsigned-integer-overflow-defined-behavior-but-signed-integer-overflow-is
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <limits>

int main() 
{
    long long v = std::numeric_limits<unsigned int>::max() + 0xf0000001LL ;
	unsigned int u ;
    int i ;
    
    u = v ; // narrowing; destination type is unsigned, the resulting value is v % 2^n
            // where n is the number of bits used to represent unsigned int (0xf0000000)
    
    i = v ; // narrowing; destination type is signed, the value is implementation-defined 
            // may be (usually is) v % 2^n interpreted as a signed value
    
    std::cout << u << ' ' << i << ' ' << 0xf0000000LL << '\n' ;
    
    double f = v ;
    
    bool b = f ; // floating point to bool conversion, non-zero, true
    
    u = f ; // floating point to integral conversion; value (after discarding fractional part) 
            // can't be represented in the integral type; undefined behaviour
    
    i = f ; // floating point to integral conversion; value (after discarding fractional part) 
            // can't be represented in the integral type; undefined behaviour

    std::cout << std::boolalpha << b << ' ' << u << ' ' << i << '\n' ;
}

http://coliru.stacked-crooked.com/a/f82d76b7e7fe8227
Topic archived. No new replies allowed.