I am trying use auto
to infer the type.
for (auto i = remaining_group.size() - 1; i >= 0; --i) {
std::cout << i;
}
I get very large number like 18446744073709534800 which is not expected. When I change auto
to int
it is the number I expected between 0 and 39.
Is there any reason auto
will fail here?
remaining_group
's type is a std::vector<lidar_point>
and lidar_point
is struct like:
struct LidarPoint {
float x;
float y;
float z;
uint8_t field1;
double field2;
uint8_t field3;
uint16_t field4;
}
When using auto
the type of i
would be std::vector::size_type
, which is an unsigned integer type. That means the condition i >= 0;
would be always true
, and if overflow happens you'll get some large numbers.
Unsigned integer arithmetic is always performed modulo 2n where n is the number of bits in that particular integer. E.g. for
unsigned int
, adding one toUINT_MAX
gives0
, and subtracting one from 0
givesUINT_MAX
.