Re: C89, size_t, and long



Yevgen Muntyan <muntyan.removethis@xxxxxxxx> wrote:

Eric Sosman wrote:
- To answer the question, you might do that to print the
size_t value using "%lu" or something of the kind. In this
case, you could get the wrong answer printed, which might or
might not affect the behavior of the rest of the program. As
far as I can imagine, this is the only case you need to worry
about, the only case in "legitimate" code where the fact that
size_t is wider than unsigned long could cause trouble.

You're saying it's legitimate.

Well, he says it's "legitimate". In this case, the scare quotes are
important. It's not more or less legal than other cases; but in this
case, it's inevitable, while in other cases, it can be avoided.

But how is casting size_t to unsigned long more legitimate than

int process_some_data (char *data, unsigned long len);

In this case, you could easily make len a size_t instead. Making it an
unsigned long instead is legal C90, but relying on this legality is
perhaps not a good idea, and making it a size_t means you get a
declaration which is more self-documenting for the cost, not of more,
but even of _less_ typing, which patently _is_ a good idea.

In the case of printf(), there's nothing you can easily do in C90 to
avoid having to cast a size_t to an unsigned long. C99 has "%zu", but
that's no help in C90, which does not.

Therefore, assuming a size_t is no larger than an unsigned long is
_legal_ in all cases in C90; but you only have _good reason_ for doing
so in the printf() case.

Richard
.



Relevant Pages

  • Re: C89, size_t, and long
    ... You're saying it's legitimate. ... but I can easily imagine how I use code which uses long instead ... unsigned long instead is legal C90, but relying on this legality is ... stddef.h in library headers due to bugs in C implementations ...
    (comp.lang.c)
  • Re: standard memory allocator alignment issue...
    ... of the undefined behavior in the printf() call. ... (easy in C90, hard in C99) ...
    (comp.lang.c)
  • Re: preprocessor and macros
    ... With C90, the solution is ... #define MYTRACEprintf s ... The problem is redefining MYTRACE above to do nothing. ... Perhaps some compilers would do a nice job with ...
    (comp.lang.c)
  • Re: preprocessor and macros
    ... C99 provides a means to do this. ... With C90, the ... #define MYTRACEprintf s ... -- R. J. Hanlon ...
    (comp.lang.c)
  • Re: preprocessor and macros
    ... With C90, the ... Call a wrapper function rather than printf(), ... pass the args to vfprintf() along with stderr. ...
    (comp.lang.c)