size_t vs int warning

前端 未结 5 1080
小鲜肉
小鲜肉 2020-12-14 15:08

I am getting following warning always for following type of code.

std::vector v;
for ( int i = 0; i < v.size(); i++) {
}

warning C

5条回答
  •  一生所求
    2020-12-14 15:39

    What is size_t?
    size_t corresponds to the integral data type returned by the language operator sizeof and is defined in the header file (among others) as an unsigned integral type.

    Is it okay to cast size_t to int?
    You could use a cast if you are sure that size is never going to be > than INT_MAX.

    If you are trying to write a portable code, it is not safe because,

    size_t in 64 bit Unix is 64 bits
    size_tin 64 bit Windows is 32 bits

    So if you port your code from Unix to WIndows and if above are the enviornments you will lose data.

    Suggested Answer

    Given the caveat, the suggestion is to make i of unsigned integral type or even better use it as type size_t.

提交回复
热议问题