Search code examples
c++type-deduction

How to understand auto deduce in for loop?


Initial value of i don't equal 5, output countless number.

int main() {
  vector<int> nums = {1, 2, 1};
  auto size = nums.size();
  for(auto i = 2 * size - 1; i >= 0; i--) {
    // do_stuff()
    std::cout << i << " ";
  }
  std::cout << std::endl;
  return 0;
}

Solution

  • Your issue stems from the fact that the type of i is unsigned, so i >= 0 is always true, rendering the loop infinite.

    i is deduced to be of the same type as size, and size is deduced to be of type size_t because vector::size() returns size_t.

    Because of above, and unsigned integer overflow, your loop is infinite. It prints (*)

    5 4 3 2 1 0 4294967295 4294967294 4294967293 ... 3 2 1 0 4294967295 4294967294 ...
    

    to infinity and beyond.

    (*) if size_t is 32 bits on your platform.