Adding or assigning an integer literal to a size_t

前端 未结 3 820
你的背包
你的背包 2021-01-11 17:36

In C I see a lot of code that adds or assigns an integer literal to a size_t variable.

size_t foo = 1;
foo += 1;

What conversi

3条回答
  •  长情又很酷
    2021-01-11 18:28

    foo += 1 means foo = foo + 1. If size_t is narrower than int (that is, int can represent all values of size_t), then foo is promoted to int in the expression foo + 1.

    The only way this could overflow is if INT_MAX == SIZE_MAX. Theoretically that is possible, e.g. 16-bit int and 15-bit size_t. (The latter probably would have 1 padding bit).

    More likely, SIZE_MAX will be less than INT_MAX, so the code will be implementation-defined due to out-of-range assignment. Normally the implementation definition is the "obvious" one, high bits are discarded, so the result will be 0.

    As a practical decision I would not recommend mangling your code to cater to these cases (15-bit size_t, or non-obvious implementation-definition) which probably have never happened and never will. Instead, you could do some compile-time tests that will give an error if these cases do occur. A compile-time assertion that INT_MAX < SIZE_MAX would be practical in this day and age.

提交回复
热议问题