Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast ssize_t or size_t

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(sst == st){...}

I would like to get rid of the warning:

warning: comparison between signed and unsigned integer expressions

But I am not sure, which variable should I cast to the other?

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

or

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

What is safer, better, cleaner? Thanks

like image 452
rluks Avatar asked Apr 18 '13 14:04

rluks


People also ask

What is the difference between Ssize_t and Size_t?

In short, ssize_t is the same as size_t , but is a signed type - read ssize_t as “signed size_t ”. ssize_t is able to represent the number -1 , which is returned by several system calls and library functions as a way to indicate error. For example, the read and write system calls: #include <sys/types.

Should I use Size_t or int?

The signed equivalent of size_t is ptrdiff_t , not int . But using int is still much better in most cases than size_t. ptrdiff_t is long on 32 and 64 bit systems. This means that you always have to convert to and from size_t whenever you interact with a std::containers, which not very beautiful.

Is Size_t same as unsigned long?

One standard recommendation is that the size_t be at most as big as an unsigned long. So you may think that we can use unsigned long in the place of size_t, but unsigned long on 64-bit system, if the OS ins Windows, will be of 32-bits, but size_t will be of 64-bits.

Is Size_t unsigned or signed?

size_t is the unsigned integer type of the result of sizeof , _Alignof (since C11) and offsetof, depending on the data model. The bit width of size_t is not less than 16.


1 Answers

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.

like image 53
Stephen Canon Avatar answered Sep 17 '22 20:09

Stephen Canon