R
Robert Hayes
I have read that size_t can hold an unsigned int. I have been playing
with using size_t as a return value and I am not sure I should. I
wrote the following code to demonstrate the issue:
#include <stdio.h>
#include <stdlib.h>
static size_t test(size_t test2) {
size_t a;
a = test2;
return a;
}
int main(int argc, char **argv) {
size_t b,c;
b = -1;
c = test(b);
if (c == -1)
printf("here\n");
else
printf("there\n");
printf("c = %zu\n",c);
return 0;
}
When b is -1 I see:
here
c = 18446744073709551615
When b is 3 I see:
there
c = 3
While I realize using an unsigned int to store a negative number is
not proper, why does it sort of work? By sort of work I mean the
comparison works but the printf doesn't. However if I change the
printf("c = %zu\n",c); to printf("c = %d\n",c) then when b is -1 I see
here and c = -1.
So should I use a size_t to hold -1? If not why does the comparison
work? I am using Ubuntu Lucid.
Thanks,
with using size_t as a return value and I am not sure I should. I
wrote the following code to demonstrate the issue:
#include <stdio.h>
#include <stdlib.h>
static size_t test(size_t test2) {
size_t a;
a = test2;
return a;
}
int main(int argc, char **argv) {
size_t b,c;
b = -1;
c = test(b);
if (c == -1)
printf("here\n");
else
printf("there\n");
printf("c = %zu\n",c);
return 0;
}
When b is -1 I see:
here
c = 18446744073709551615
When b is 3 I see:
there
c = 3
While I realize using an unsigned int to store a negative number is
not proper, why does it sort of work? By sort of work I mean the
comparison works but the printf doesn't. However if I change the
printf("c = %zu\n",c); to printf("c = %d\n",c) then when b is -1 I see
here and c = -1.
So should I use a size_t to hold -1? If not why does the comparison
work? I am using Ubuntu Lucid.
Thanks,