Insert ssize_t or size_t

In the source files that I use in my project, there is a comparison between the ssize_t and size_t variables:

 ssize_t sst; size_t st; if(sst == st){...} 

I would like to get rid of the warning:

 warning: comparison between signed and unsigned integer expressions 

But I'm not sure which variable I should give to another?

 if((size_t)sst == st){...} 

or

 if(sst == (ssize_t)st){...} 

Which is safer, better, cleaner? Thanks

+7
source share
2 answers

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

  • If you know that sst non-negative, then you can safely discard sst in size_t , as that will not change the value (by the way, this is what happens if you don't have a role at all).

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

  • If sst can be negative, and st can be greater than SSIZE_MAX , then none of them is correct; or you can change the value, which will lead to an incorrect comparison. Instead, you will do the following if (sst >= 0 && (size_t)sst == st) .

If you are not absolutely sure that one of the first two situations applies, select the third option, since it is correct in all cases.

+16
source

Or it will work fine if both values ​​correspond to the positive representable range ssize_t .

If any value does not work, you may run into a problem - check these cases before testing for equality:

 if ((sst >= 0) && (st <= SSIZE_MAX) && (sst == (ssize_t)st)) { ... } 

(I am sure that C ++ people recommend that you completely abandon C-style - I have no doubt that someone will comment or respond and tell you the correct way to do this in C ++.)

+3
source

All Articles