Reputation: 519
I have a program which outputs a value, call it x
which could be of any numerical type. When I typecast x
as (int)x
, for positive numbers it works fine, but for negative numbers it seems to be treated it as unsigned. (Doing a modulo INT_MAX +1).
I use it as an array index, and suddenly I was getting many "out_of_range" errors, so I inserted some printfs and made x an integer, and I got this as my output:
Before: 44 After: 44
Before: -60 After: 4294967236
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check
Aborted (core dumped)
with the command:
std::cout << "Before: " << 2*total_sites + energy_base << "\tAfter: " << 2*total_sites + (int)energy_base << std::endl;
where energy_base
is the "x" I used in my example.
energy_base itself is defined as a double, but it is generated from a function which (for this example), I have restricted to "integer" values. For context, total_sites is an unsigned integer.
Where am I going wrong?
Upvotes: 2
Views: 62
Reputation: 280207
In unsigned + signed, unsigned wins. (int) energy_base
is converted to an unsigned int for the addition with 2*total_sites
.
Upvotes: 5