This is a discussion on Re: more improvements for mg within the mailing.openbsd.tech forums, part of the OpenBSD category; --> On Mon, May 16, 2005 at 09:59:04AM -0600, Todd C. Miller wrote: > In message <20050516151748.GA1337@moule.localdomain> > so spake ...
| |||||||
| Register | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
| ||||
| On Mon, May 16, 2005 at 09:59:04AM -0600, Todd C. Miller wrote: > In message <20050516151748.GA1337@moule.localdomain> > so spake Alexandre Ratchov (alex-contact): > > > int ret; > > char foo[100]; > > > > ... > > ret = snprintf(foo, sizeof(foo), "%s", input); > > if (ret < 0 || (size_t)ret >= sizeof(foo)) > > > > > > -1 means that snprintf failed and negative number of chars is meaningless. > > This works if sizeof(foo) > INT_MAX because res is converted to size_t. > > Have i missed something? > > While this does look OK I really don't see the need for the cast > to size_t. In practice sizeof(foo) will not be > INT_MAX unless > you are creating 2GB data structures on the stack and the stack is > not big enough to hold such a data structure anyway. I agree that cast is not necessary since even lint doesn't complain about it. It doesn't hurt to have the cast either, since that cast _will_ happen implicitly anyway. In the above program it doesn't matter since a positive number has a 0 for the most significant bit and remains the same when cast to unsigned. If sizeof returns size_t, and size_t is typedefed as unsigned int, according to the implicit expression casting rules, int _will_ be cast into unsigned when compared to an unsigned number. For example this program #include <stdio.h> #include <limits.h> int main(int argc, char *argv[]) { int x = INT_MIN; size_t y = INT_MAX; printf("INT_MIN = %d\nINT_MAX = %d\n", INT_MIN, INT_MAX); if (x > y) printf("\nCast: INT_MIN > INT_MAX unsigned\n"); return 0; } produces $ make tryme cc -O2 -o tryme tryme.c $ ./tryme INT_MIN = -2147483648 INT_MAX = 2147483647 Cast: INT_MIN > INT_MAX unsigned Thus, with or without explicit cast to size_t, the cast will happen. Regards, Zvezdan Petkovic |