简体   繁体   中英

Typecasted signed int converting like unsigned int

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?

In unsigned + signed, unsigned wins. (int) energy_base is converted to an unsigned int for the addition with 2*total_sites .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM