Re: printf and size_t
- From: "rayw" <ray.webster@xxxxxxxxx>
- Date: 8 Aug 2006 09:08:54 -0700
Richard Heathfield wrote:
ray.webster@xxxxxxxxx said:
Richard Heathfield wrote:
ray.webster@xxxxxxxxx said:
I'm using gcc 3.4.2 and the output is zu, this, I believe, shows that
the printf supplied doesn't recognize %zu as a valid format specifier?
Yes, it shows that the libc you are using is not C99-conforming.
Ah, so the gcc I'm using hasn't come complete with a libc that's also
compliant.
Hold on there - what makes you think the compiler is C99-conforming?!?
Because this ...
# if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
/* C99, so it should support %zu?
*/
printf("%zu", t);
...
outputs 'zu' - so it looks as though my gcc says that it's c99
compliant (__STDC_VERSION__ isn't defined in stdio.h (which is all I
have included) so I'm assuming it's defined 'internally' by the
compiler - which certainly sounds like it ought to work that way, e.g.,
that you 'ask' the compiler rather that 'trust' an include file)?
<snip>
So, if %zu isn't supported, and I can't get a libc that does support
it, is %lu ok - or - should I use unsigned long long?
Use: printf("%lu\n", (unsigned long)sizeof object);
unless you are likely to be dealing with objects greater than 4294967295
bytes in size, in which case make sure first that unsigned long is big
enough. If you are and it isn't, you may be forced to use unsigned long
long if your compiler supports it.
Even then, as far as I know, there's no way to know whether even that
has enough bits to hold a size_t (right?) - should I check that with an
assertion say - that sizeof(size_t) <= sizeof(unsigned long) etc?
Well, that's why you need to cast - because printf is variadic, the
arguments you supply to it won't automagically be converted, so you have to
be very careful with types. But provided the /value/ fits inside an
unsigned long, the cast is necessary and sufficient.
Does this look ok?
int main(void)
{
size_t t = 42;
# if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
/* C99, so it should support %zu?
*/
printf("%zu", t);
# else
/* Not a C99.
**
** Use unsigned long OR unsigned long long instead.
*/
# if sizeof(size_t) <= sizeof(unsigned long)
printf("%lu", (unsigned long)t);
# else
printf("%llu", (unsigned long long)t);
# endif
# endif
return 0;
}
.
- Follow-Ups:
- Re: printf and size_t
- From: Keith Thompson
- Re: printf and size_t
- From: Richard Heathfield
- Re: printf and size_t
- References:
- printf and size_t
- From: ray . webster
- Re: printf and size_t
- From: Richard Heathfield
- Re: printf and size_t
- From: ray . webster
- Re: printf and size_t
- From: Richard Heathfield
- printf and size_t
- Prev by Date: Re: Could somebody tell me the difference?
- Next by Date: Difference between exit(0) & exit (1)
- Previous by thread: Re: printf and size_t
- Next by thread: Re: printf and size_t
- Index(es):
Relevant Pages
|
|