acceptable fix for majority of signed/unsigned warnings?

后端 未结 7 700
清酒与你
清酒与你 2021-01-12 03:32

I myself am convinced that in a project I\'m working on signed integers are the best choice in the majority of cases, even though the value contained within can never be neg

7条回答
  •  独厮守ぢ
    2021-01-12 03:50

    I made this community wiki... Please edit it. I don't agree with the advice against "int" anymore. I now see it as not bad.

    Yes, i agree with Richard. You should never use 'int' as the counting variable in a loop like those. The following is how you might want to do various loops using indices (althought there is little reason to, occasionally this can be useful).

    Forward

    for(std::vector::size_type i = 0; i < someVector.size(); i++) {
        /* ... */
    }
    

    Backward

    You can do this, which is perfectly defined behaivor:

    for(std::vector::size_type i = someVector.size() - 1; 
        i != (std::vector::size_type) -1; i--) {
        /* ... */
    }
    

    Soon, with c++1x (next C++ version) coming along nicely, you can do it like this:

    for(auto i = someVector.size() - 1; i != (decltype(i)) -1; i--) {
        /* ... */
    }
    

    Decrementing below 0 will cause i to wrap around, because it is unsigned.

    But unsigned will make bugs slurp in

    That should never be an argument to make it the wrong way (using 'int').

    Why not use std::size_t above?

    The C++ Standard defines in 23.1 p5 Container Requirements, that T::size_type , for T being some Container, that this type is some implementation defined unsigned integral type. Now, using std::size_t for i above will let bugs slurp in silently. If T::size_type is less or greater than std::size_t, then it will overflow i, or not even get up to (std::size_t)-1 if someVector.size() == 0. Likewise, the condition of the loop would have been broken completely.

提交回复
热议问题