Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C size_t and ssize_t negative value

Tags:

c

size-t

size_t is declared as unsigned int so it can't represent negative value.
So there is ssize_t which is the signed type of size_t right?
Here's my problem:

#include <stdio.h>
#include <sys/types.h>

int main(){
size_t a = -25;
ssize_t b = -30;
printf("%zu\n%zu\n", a, b);
return 0;
}

why i got:

18446744073709551591
18446744073709551586

as result?
I know that with size_t this could be possible because it is an unsigned type but why i got a wrong result also with ssize_t??

like image 395
polslinux Avatar asked Aug 29 '12 09:08

polslinux


People also ask

Can Size_t have negative values?

The size_t data type is never negative.

What happens if Size_t is negative?

The standard specifies that size_t is an "unsigned integer type." If you declare a parameter of type size_t and try to pass a negative value as an argument in a call to the function, the compiler should be emitting a warning about type conversion.

What is the difference between Size_t and Ssize_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.

Is Size_t guaranteed to be unsigned?

Yes, size_t is guaranteed to be an unsigned type.


1 Answers

In the first case you're assigning to an unsigned type - a. In the second case you're using the wrong format specifier. The second specifier should be %zd instead of %zu.

like image 154
cnicutar Avatar answered Sep 19 '22 03:09

cnicutar