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
??
The size_t data type is never 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.
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.
Yes, size_t is guaranteed to be an unsigned type.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With