Is it safe to use negative integers with size_t?

后端 未结 4 1692
旧巷少年郎
旧巷少年郎 2021-02-20 17:52

I just saw some C++ code like this. It was using a condition to decide whether to walk forward or backward through a std::vector. The compiler doesn\'t complain, b

4条回答
  •  野的像风
    2021-02-20 18:42

    Is it safe to use negative integers with size_t?

    No, it is dangerous. Overflow.

    size_t a = -1;
    std::cout << a << "\n";
    

    Output:

    4294967295 // depends on the system, largest value possible here
    

提交回复
热议问题