Cast ssize_t or size_t

前端 未结 2 1835
故里飘歌
故里飘歌 2021-02-14 01:15

In source files which I am using in my project, there is a comparison between ssize_t and size_t variables:

ssize_t sst;
size_t st;

if         


        
2条回答
  •  Happy的楠姐
    2021-02-14 01:38

    There is no one right answer to this question. There are several possible answers, depending on what you know a priori about the values that those variables may take on.

    • If you know that sst is non-negative, then you can safely cast sst to size_t, as this will not change the value (incidentally, this is what happens if you have no cast at all).

    • If sst might be negative but you know that st will never be larger than SSIZE_MAX, then you can safely cast st to ssize_t, as this will not change the value.

    • If sst might be negative, and st might be larger than SSIZE_MAX, then neither cast is correct; either one could change the value, resulting in an incorrect comparison. Instead, you would do the following if (sst >= 0 && (size_t)sst == st).

    If you’re not absolutely certain that one of the first two situations applies, choose the third option as it is correct in all cases.

提交回复
热议问题