I have size_t file_size;
variable declared in my c file which will get -1
assigned to it later and then when I do
if(file_size < 0) {
// do something
} else {
printf("C is confusing\n");
}
output: C is confusing
but if I set my condition to
if(file_size == -1) {
printf("C is easy\n");
} else {
// do something
}
output: C is easy
Can someone please explain why there is even a remote chance that this could be happening. Thanks in advance!
Both cases are related to the fact the size_t
is unsigned, i.e. it can represent only non-negative values.
When you assign -1
to it you actually get the unsigned equivalent (bitwise) of it. Since most (if not practically all) systems use 2s complement to represent negative integers, you will get a value where all bits are 1
. For example, on systems where size_t
is 32-bit, it will be assigned the value 0xFFFFFFFF (32 1
s in binary).
The 1st case:
Since it is unsigned
it can never be < 0
.
The 2nd case:
When you compare it to -1
, the -1
is actually converted to unsigned value (all 1
s in binary as explained above), and the equality is then feasible.
On a POSIX system (or similar), if you want to represent negative values properly, you can use ssize_t
instead of size_t
(it's the signed version of it).
It requires #include <sys/types.h>
.