Reputation: 10425
For example I have the following:
#include <iostream>
int main()
{
long long a = 2346436346346346;
int b = a;
//int b = static_cast<int>(a) //same result
std::cout << a << "\n" << b;
std::cin.get();
}
Output:
2346436346346346
1223261034
By what logic does b
take that value?
Upvotes: 1
Views: 109
Reputation: 50111
The result of an overflowing assignment to a signed integer type is implementation defined:
If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.
(4.7 Clause 3 in N4140)
So you would have to ask whoever provides your implementation what they say the result will be, the C++ standard does not say anything in regards to that.
Upvotes: 9
Reputation: 42929
According to the standard 4.7\p3 Integral conversions [conv.integral] (Emphasis Mine):
If the destination type is signed, the value is unchanged if it can be represented in the destination type; otherwise, the value is implementation-defined
Upvotes: 2
Reputation: 29986
By what logic does b take that value?
It is implementation-defined, in your case the value is truncated:
2346436346346346 in binary is:
0000000000001000 0101011000010010 0100100011101001 0111101101101010
1223261034 in binary is:
0100100011101001 0111101101101010
Upvotes: 8